使用 strcat 时添加的随机空格
Random spaces added when using strcat
我正在尝试不断将字符添加到字符串的末尾。我正在通过 运行 在我的 main
中执行此操作
char String[256];
char alphabets[26] = "abcdefghijklmnopqrstuvxyz";
for (int i = 0; i < 257; i++) {
char newChar = alphabets[indexOfNewChar-1];
printf("new char = %c\n",newChar);
strcat(String,&newChar);
printf("%s\n",String);
}
当我运行打印这堆代码的时候
new char = b
bkhobtj
dfhhai bbdhgfcafgcfi bbaccfeai afebaci aedgdddai hei hfedhbi dabeedbi i cfhi i caddbhgbi i acfi cehbhcddcahbhbabi aaadi hi ffhhccbccfbbfggfdhebgeacecai cefdcdb
如您所见,在 运行 期间 运行domly 出现了空格和新行。
在意识到这些 运行dom 空间的外观运行ces 之后,我尝试用
删除空格
char* removeSpaces(char* input)
{
int i,j;
char *output=input;
for (i = 0, j = 0; i<strlen(input); i++,j++)
{
if (input[i]!=' ')
output[j]=input[i];
else
j--;
}
output[j]=0;
return output;
}
然而,这并没有真正影响结果,因为仍然出现运行空格。我怎样才能删除那些空格或更好地阻止它们出现。
在旁注中,代码在 for 循环重复 160 多次后终止。我该如何克服这个问题。
newChar
是单个char
; &newChar
是 不是 字符串。字符串需要空终止符; strcat
正在寻找一个,并连接它找到的杂散字符,直到找到一个(尽管这是未定义的行为,因此它可能导致程序崩溃)。
我正在尝试不断将字符添加到字符串的末尾。我正在通过 运行 在我的 main
中执行此操作 char String[256];
char alphabets[26] = "abcdefghijklmnopqrstuvxyz";
for (int i = 0; i < 257; i++) {
char newChar = alphabets[indexOfNewChar-1];
printf("new char = %c\n",newChar);
strcat(String,&newChar);
printf("%s\n",String);
}
当我运行打印这堆代码的时候
new char = b
bkhobtj
dfhhai bbdhgfcafgcfi bbaccfeai afebaci aedgdddai hei hfedhbi dabeedbi i cfhi i caddbhgbi i acfi cehbhcddcahbhbabi aaadi hi ffhhccbccfbbfggfdhebgeacecai cefdcdb
如您所见,在 运行 期间 运行domly 出现了空格和新行。 在意识到这些 运行dom 空间的外观运行ces 之后,我尝试用
删除空格char* removeSpaces(char* input)
{
int i,j;
char *output=input;
for (i = 0, j = 0; i<strlen(input); i++,j++)
{
if (input[i]!=' ')
output[j]=input[i];
else
j--;
}
output[j]=0;
return output;
}
然而,这并没有真正影响结果,因为仍然出现运行空格。我怎样才能删除那些空格或更好地阻止它们出现。 在旁注中,代码在 for 循环重复 160 多次后终止。我该如何克服这个问题。
newChar
是单个char
; &newChar
是 不是 字符串。字符串需要空终止符; strcat
正在寻找一个,并连接它找到的杂散字符,直到找到一个(尽管这是未定义的行为,因此它可能导致程序崩溃)。