使用c中的文件

Working with files in c

本文关键字:文件 使用      更新时间:2023-10-16

如何从字符串中删除每个不是字母的字符从字符串CCD_ 1,我需要一个输出afhbi。请注意,考虑到我不想要逗号和其他类似的符号。到目前为止,这是我的代码,它不起作用,有什么提示吗?

while((fgets(str,30,fpointer))!=NULL)
{ //i get a string
    for(i=0;i<strlen(str);i++)//going thru the string
    if(isalpha(str[i])){strcat(Need,str[i]);}
      //if the char is alpha put it in a new  string called Need
}

您不希望使用strcat向数组添加字符。这是为了将一个字符串附加到另一个字符串上。只需在数组中插入字符。

int j = 0;    // Index of the new string
for(i = 0; i < strlen(str); i++) {   //going thru the string
    if(isalpha(str[i])) {
        Need[j++] = str[i];
    }
}
Need[j] = 0;   // Make sure you terminate the new string

您也可以使用memmove来执行类似的操作。首先在Need中复制字符串;

Need = strdup(str);
p = Need;
q = str;
while (*q) {
    if (!isalpha(*q)) {
        len = strlen(p); 
        memmove(p, p + 1, len); // this will move the NULL terminator too
    } else {
        p++;
    }
    q++;
}

现在,Need已经清理掉了所有丑陋的非角色!