c - C语言去除字符串中的标点符号

标签 c arrays string

我正在努力删除可能存在于字符串开头或结尾或两者都存在的标点符号。 前任。 “!!你好**” 我想要一个输出:“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/

相关文章:

c - 具有非精确表示的舍入 float

c - 使用泰勒展开的正弦函数(C 编程)

javascript - 将数组中的数据映射到子组件和父组件中

c++ - Arduino 数组和 if 语句

string - 如何格式化字符串以用作 MATLAB 中的结构字段名称?

c - float 变量重置为1.000

c - fscanf 读取多个字符串

objective-c - 追加 NSMutableArray

python - 在pandas python中删除文本中的 '\n'

python - 替换字符串中的特殊字符的问题