我正在努力删除可能存在于字符串开头或结尾或两者都存在的标点符号。 前任。 “!!你好**” 我想要一个输出:“Hello”,所有标点符号都被删除。
char s[] = "!!Hello**";
ch [] = NULL;
int i = 0;
for (i = 0; i < length; i++) {
if ( isalpha(s[i]) ) {
ch[i]=s[i];
} else {
continue;
}
ch[i] = '\0';
}
代码块似乎没有将字符串复制到 ch。不知道为什么!!
最佳答案
您可以就地更改它:
#include <ctype.h>
#include <stdio.h>
int main() {
char s[] = "!!Hello**";
size_t pos = 0;
for (char *p = s; *p; ++p)
if (isalpha(*p))
s[pos++] = *p;
s[pos] = '\0';
printf("'%s'\n", s);
}
输出
'Hello'
或者只使用指针:
#include <ctype.h>
#include <stdio.h>
void filter_alpha(char *s) {
for (char *p = s; *p; ++p)
if (isalpha(*p))
*s++ = *p;
*s = '\0';
}
int main() {
char s[] = "!!Hello**";
filter_alpha(s);
printf("'%s'\n", s);
}
仅删除前导/尾随非字母字符
#include <assert.h>
#include <ctype.h> // isalpha()
#include <stdio.h>
#include <string.h> // strlen()
char* strip_nonalpha_inplace(char *s) {
for ( ; *s && !isalpha(*s); ++s)
; // skip leading non-alpha chars
if (*s == '\0')
return s; // there are no alpha characters
assert(isalpha(*s));
char *tail = s + strlen(s);
for ( ; !isalpha(*tail); --tail)
; // skip trailing non-alpha chars
assert(isalpha(*tail));
*++tail = '\0'; // truncate after the last alpha
return s;
}
int main() {
char s[] = "!!Hello**";
printf("'%s'\n", strip_nonalpha_inplace(s));
}
关于c - C语言去除字符串中的标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283555/