c - 从 C 中的字符串中删除数字和除撇号之外的所有标点符号

标签 c string char

我正在编写一些代码,该代码将字符串作为参数并将字母字符变为小写,删除数字(012...9),并删除除撇号之外的所有标点符号。到目前为止,这是我的代码:

void stripLower(char* str) {
    int strLen = strlen(str);
    char* temp[strLen];
    char apos = (char)"39";

    for(int i = 0; i < strLen; i++) {
        if(isupper(str[i])){
            str[i] = tolower(str[i]);
        } else if(isdigit(str[i])) {
            str[i] = (char)"0";
        } else if(ispunct(str[i])){
            /*if((strcmp(str[i], apos)) == 0){

            } else {
                str[i] = (char)"0";
            }*/
        }
    }

    /*for(int i = 0; i < strLen; i++){
        str[i] = temp[i];
    } */
}

我的第一个问题是我是否正确地从字符串中删除了数字?我的另一个问题是如何去掉除撇号之外的所有标点符号?我注释掉了我尝试过的一些代码,因为它会阻止我的其余代码正常运行。

最佳答案

您混淆了字符串和字符。字 rune 字包含在 ' 中。字符串文字包含在 " 中,是一个字符数组。

例如:

"This is a string literal"
'c' // this is character

例如,要测试 char 是否不是 z,您可以编写:

char c = ...;    
if (c == 'z')

对于特殊字符,例如 '、换行符、制表符等,您必须像这样转义它们:

char c1 = '\'' // this is a ' character
char c2 = '\t' // this is a tab character

strcpm 用于比较字符串。如果您想比较字符,== 就是您所需要的,如我上面所示。

<小时/>

你的函数可以简单地写成这样:

int strip(char* str)
{
    int from, to;       
    for (from = 0, to = 0; str[from] != '\0'; ++from) {
        if (!isdigit(str[from]) && (!ispunct(str[from]) || str[from] == '\'')) {
            str[to] = tolower(str[from]);
            ++to;
        }
    }
    str[to] = '\0';
}

示例输入和输出:

int main(void)
{
    char str[] = "This is 'Sparta'! The 200. I ,think,";
    strip(str);
    printf("%s\n", str);
    return 0;
}

输出:

this is 'sparta' the  i think

关于c - 从 C 中的字符串中删除数字和除撇号之外的所有标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564334/

相关文章:

c# - 从 C# 调用 C DLL 函数 - 将 char 参数转换为字符串

java - Id.CharAt() 的整数版本

c++ - 逐个字符地添加字符串到 2dim 数组中

c - 反四元数

android - 如何在 onCreate() 之前在静态字符串上使用 getString()?

c - 如何计算C中的进程CPU使用率?

c++ - 反转字符串中的每个单词(应该处理空格)

java - 将 Bash 字符串转换为 Java 字符串

c - 如何在C中创建一组随机数

c++ - 在 Visual Studio Code 中设置相对于工作区路径的 c/c++ 项目路径(.json 配置)