首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C中删除字符串中的标点符号

问在C中删除字符串中的标点符号
EN

Stack Overflow用户
提问于 2012-02-15 04:14:59
回答 4查看 5.4K关注 0票数 1

我正在致力于删除标点符号,这些标点符号既可以存在于字符串的开头或结尾,也可以同时存在于字符串的开头和结尾。例如。"!!Hello**“我想要一个输出:"Hello”,去掉所有的标点符号。

代码语言:javascript
复制
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。不知道为什么!

EN

回答 4

Stack Overflow用户

发布于 2012-02-15 04:22:22

您可以在原地更改它:

代码语言:javascript
复制
#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);
}

输出

代码语言:javascript
复制
'Hello'

或者只使用指针:

代码语言:javascript
复制
#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);
}

仅删除前导/尾随非字母字符

代码语言:javascript
复制
#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));
}
票数 3
EN

Stack Overflow用户

发布于 2012-02-15 04:39:11

您的想法似乎是正确的,但是在处理C语言中的字符串时,您遗漏了一些重要的东西(比如strlen)。

这将删除任何前导和尾随的非字母数字ASCII字符。

代码语言:javascript
复制
#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。

票数 1
EN

Stack Overflow用户

发布于 2012-02-15 04:18:55

您的代码有几个问题:

代码语言:javascript
复制
ch [] = NULL;

它的定义中应该有一个类型:

代码语言:javascript
复制
char ch[15];

不要定义未定义大小的char数组。

另外,您的代码中的length是什么?您可以使用strlen(s)而不是length,因为我没有看到它的定义。

对于标记化,您可以使用strtok。

要将字符串从一个数组复制到另一个数组,请使用strcpy_s。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9283555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档