c - 在 C 中复制字符串时出现意外符号

标签 c string copy

我需要从字符串中过滤非字母字符并将所有字符转换为小写。我正在使用以下内容:

void filter(char orig[], char filtered[]) {

    int i;
    for (i = 0; orig[i] != '\0'; ++i){
        if(isalpha(orig[i])){
            filtered[i] = tolower(orig[i]);
        }
    }

    return ;
}

但是,由于字符出现在末尾,我的测试失败了。我做错了什么?

enter image description here

最佳答案

您必须终止目标字符串,并且您跳过了非字母的字符位置

void filter(char orig[], char filtered[]) {

    int i, j = 0;                               // separate index for filtered[]
    for (i = 0; orig[i] != '\0'; ++i){
        if(isalpha(orig[i])){
            filtered[j++] = tolower(orig[i]);   // inc index
        }
    }
    filtered[j] = '\0';                         // terminate string
    return ;
}

关于c - 在 C 中复制字符串时出现意外符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29353008/

相关文章:

c - Couchbase 在多大程度上可以替代 Memcached

c# - 在 C# 中避免数字格式中的额外零

python pandas - 生成具有多个条件的 View /复制警告过滤数据框

c# - 如何根据是否可以复制来启用和禁用按钮?

C:中缀到后缀转换的堆栈转储错误

c - 将字符串中的每个子字符串存储在数组中

string - 有没有关于如何实现二维 KMP 的论文或解释?

python - 尝试复制 pyside 对象时出现问题

使用C语言更改GRUB的变量

string - uint16到xx.x float —最快的算法?