首页 > 解决方案 > 无法更改 C 中字符串的最后一个索引的内容?

问题描述

我目前在更改字符串内容方面遇到一些问题。

我正在编写的以下程序重新排列字符串 src 中以辅音开头的单词,使辅音在后面结束(bob --> obb)。以元音开头的单词保持不变。结果被插入到字符串 dest。

然而,句子输入的最后一个词总是以一个缺失的辅音结尾(bob --> ob)。这表明我无法更改字符串 dest 的最后一个索引的内容。

有什么原因吗?

void convert(char src[], char dest[]) {
    int i, isVowel, first_pos;
    int len = strlen(src);
    int count = 0;
    char first = 0;

    for (i = 0; i < len; i++) {
        while (!isspace(src[i])) {

            if (first == 0) {
                first = src[i];
                first_pos = i;
            }

            isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';

            if (isVowel == 1) {
                dest[count++] = src[i];
            }   
            else if (i != first_pos) {
                dest[count++] = src[i];
            }   

            i++;
        }   

        if (isVowel == 0) {
            dest[count++] = first;
        }   

        dest[count++] = ' ';
        first = 0;
      }
}

输入:“hi guy” 预期输出:“ih uysg” 实际输出:“ih uys”

标签: cstringcharacter

解决方案


你应该改变

while (!isspace(src[i])) {

while (src[i] && !isspace(src[i])) {

最后添加功能

dest[count++] = '\0';

修改后的代码:

void convert(char src[], char dest[]) {
    int i, isVowel, first_pos;
    int len = strlen(src);
    int count = 0;
    char first = 0;

    for (i = 0; i <= len; i++) {
        while (src[i] && !isspace(src[i])) {

            if (first == 0) {
                first = src[i];
                first_pos = i;
            }

            isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';

            if (isVowel == 1) {
                dest[count++] = src[i];
            }   
            else if (i != first_pos) {
                dest[count++] = src[i];
            }   

            i++;
        }   

        if (isVowel == 0) {
            dest[count++] = first;
        } 

        dest[count++] = ' ';
        first = 0;
      }
      dest[count++] = '\0';
}

推荐阅读