我正在编写一些代码,该代码将字符串作为参数并将字母字符变为小写,删除数字(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/