如何删除字符串中不是字母的每个字符
从字符串a,f,4,h,b
开始,
我需要输出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
}
答案 0 :(得分:1)
您不希望使用strcat
向数组添加字符。这是为了将一个字符串附加到另一个字符串。只需在数组中插入char。
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
答案 1 :(得分:0)
您也可以使用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++;
}
现在,需要清除丑陋的非角色!