任务是输出字符串中的每隔一个单词
我做了一个循环来检查字符串中的每个字符,当它到达一个空格时, bool 值会将其值更改为相反的值,因此在到达下一个空格之前,它将把字符从第一个字符串复制到第二个字符串
int main(void)
{
char str1[max]="Hellow my name is Tom why not today";
char str2[max];
int i;
bool a=false;
for (i=0;i<strlen(str1);i++)
{
if ((int)str1[i]==32)
{
a=!a;
}
if (a==true)
{
str2[i]=str1[i];
}
}
printf ("%s\n",str2);
return 0;
}
终端显示:`\365\277\357\376 my\365\277\357\376 isu
最佳答案
str1 和 str2 需要不同的索引。当 'a' 为 false 时,您不会将 i 的值写入 str2[i]。这将导致您未写入的字节中出现随机数据。这就是为什么您会在每个第二个单词之间看到垃圾数据。
int dest_index = 0;
for (i=0;i<strlen(str1);i++)
{
if ((int)str1[i]==32)
{
a=!a;
}
if (a==true)
{
str2[dest_index++]=str1[i];
}
}
str2[dest_index] = 0; // Null terminate the destination string
printf ("%s\n",str2);
关于c - 在终端中出现错误“\365\277\357\376”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662881/