我正在致力于删除标点符号,这些标点符号既可以存在于字符串的开头或结尾,也可以同时存在于字符串的开头和结尾。例如。"!!Hello**“我想要一个输出:"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。不知道为什么!
发布于 2012-02-15 04:22:22
您可以在原地更改它:
#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));
}发布于 2012-02-15 04:39:11
您的想法似乎是正确的,但是在处理C语言中的字符串时,您遗漏了一些重要的东西(比如strlen)。
这将删除任何前导和尾随的非字母数字ASCII字符。
#include <string.h>
char * remove_outer_punctuation( char * text )
{
int i = 0;
size_t len = 0;
char * start = text;
if ( text == NULL ) return NULL;
len = strlen(text);
if ( len < 1 ) return start;
// advance start to the first alphanum character
for ( i = 0 ; i < len; i++ ){
if ( !isalpha(text[i]) ) {
start++;
} else {
continue;
}
}
// find the final alphanumeric character and
// put a NUL after it
for ( i = len; i > 0; i-- ){
if ( isalpha(text[i] ) continue;
}
text[i+1] = 0x0;
return start;
}需要注意的是,这将修改输入字符串(我们插入NUL )。如果你不想这样做,首先使用strcpy。
发布于 2012-02-15 04:18:55
您的代码有几个问题:
ch [] = NULL;它的定义中应该有一个类型:
char ch[15];不要定义未定义大小的char数组。
另外,您的代码中的length是什么?您可以使用strlen(s)而不是length,因为我没有看到它的定义。
对于标记化,您可以使用strtok。
要将字符串从一个数组复制到另一个数组,请使用strcpy_s。
https://stackoverflow.com/questions/9283555
复制相似问题