繁体   English   中英

c 字符串:程序将空格后面的字符读取为空格

[英]c strings: program reads characters following a space as blank spaces

在以空格分隔的字符串中的第一个空格之后,程序将空格之后的所有字符解释为空格:

前任:

char test1[] = "hello man";
char test2[128];
    for (int i = 0; i < strlen(test1); i++){
        if (test1[i] == ' ')
            continue;
        else
            test2[i] = test1[i];
    }
    printf("%s\n", test2);

该程序输出“hello”,而不是“helloman”。 你如何让它输出“helloman”?

您可以尝试添加另一个在字符为空格时不会增加的计数索引。 例如。

int j = 0;  // added this
char test1[] = "hello man";
char test2[128];
for (int i = 0; i < strlen(test1); i++){
    if (test1[i] == ' ')
        continue;
    else {
        test2[j] = test1[i]; //changes here
        j++;                 // changes here
    } 
}
test2[j] = 0;                // added this
printf("%s\n", test2);

发生这种情况是因为test2很可能被初始化为零值字节 ( 0x0 ),并且因为您不仅跳过了test1中的索引,而且还跳过了test2中的索引。

在执行 for 循环之前,您的记忆看起来与此类似:

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ... ] # 128 times

然后将 char 从test1复制到test2之后,直到找到一个空格:

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 'h', 'e', 'l', 'l', 'o', 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ... ] # 128 times

但是,您想跳过空格,因此您continue ,但0x0字符仍保留在test2中,因为您移动到下一个索引。

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 'h', 'e', 'l', 'l', 'o', 0x0, 'm', 'a', 'n', 0x0, 0x0, 0x0, ... ] # 128 times

由于字符串在 C 中以 NULL 结尾(因此结尾由0x0字节标记),它只打印字符串的第一部分 - 直到您留在其中的0x0

为避免这种情况,您可以为test1test2数组使用单独的索引,并在找到空间时仅增加test1索引( i变量)(不增加test2索引):

int test2_index = 0;
char test1[] = "hello man";
char test2[128] = { 0 };
for (int i = 0; i < strlen(test1); i++){
    if (test1[i] == ' ') {
        continue;
    } else {
        test2[test2_index] = test1[i];
        test2_index++;
    }
}
printf("%s\n", test2);

您可以通过使用调试器并在每次 for 循环迭代后检查每个数组的内存区域来避免此类错误。 或者,由于您只有 2 个数组和 2 个索引和一个 for 循环,您可以用笔和纸跨过算法,在每一步之后跟踪每个变量的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM