我一直在嘗試反向“復制”一個字串到另一個字串。它有點作業,但它列印了一些奇怪的符號。我試過設定 char copy[length2] 但這使程式根本無法運行。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define ARR_SIZE 50
int main()
{
char string[ARR_SIZE];
printf("Enter char array!\n");
fgets(string, ARR_SIZE, stdin);
string[strlen(string) - 1] = '\0';
int length = (strlen(string) - 1);
int length2 = (strlen(string) - 1);
printf("%s\t%d\n", string, length);
for (int i = 0; i <= length; i )
{
printf("INDEX = %d CHAR = %c\n", i, string[i]);
}
printf("%d", length2);
char copy[ARR_SIZE];
for (int i = 0; i <= length2; i )
{
copy[i] = string[length];
length--;
}
printf("\n%s", copy);
}

uj5u.com熱心網友回復:
這些是我對您的代碼所做的最小修改:
#include <stdio.h>
#include <string.h>
// remove unneeded headers
#define ARR_SIZE 50
int main(void)
{
char string[ARR_SIZE];
printf("Enter char array!\n");
fgets(string, ARR_SIZE, stdin);
string[strlen(string) - 1] = '\0';
// remove the -1 on the string length calculation, the NUL terminator is not
// included in strlen's return value
int length = strlen(string);
// no sense in calling strlen twice
int length2 = length;
// fixed `length` now prints the correct length
printf("%s\t%d\n", string, length);
// change from <= to <. The array indices where the characters live are
// [0, length-1].
for (int i = 0; i < length; i )
{
printf("INDEX = %d CHAR = %c\n", i, string[i]);
}
// fixed `length2` now prints the correct length
printf("%d", length2);
char copy[ARR_SIZE];
for (int i = 0; i < length2; i )
{
// last character in `string` lives at the `length`-1 index
copy[i] = string[length-1];
length--;
}
// `length2` is the index after the last char in `copy`, this needs
// to be NUL terminated.
copy[length2] = '\0';
// prints the reversed string
printf("\n%s", copy);
}
演示
uj5u.com熱心網友回復:
- 使用函式。
- 用空字符
\0或簡單地終止字串0。
char *copyreverse(char *dest, const char *src)
{
size_t len = strlen(src);
const char *end = src len - !!len;
char *wrk = dest;
while(len--)
*wrk = *end--;
*wrk = 0;
return dest;
}
int main()
{
char dest[10];
char *src = "hello";
printf("`%s` reversed `%s`\n", src, copyreverse(dest, src));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345571.html
