【问题标题】:Strip numbers from a string in C从C中的字符串中去除数字
【发布时间】:2013-07-09 20:23:33
【问题描述】:

我正在寻找一种从字符串中去除数字的简单解决方案。 示例:“GA1UXT4D9EE1”=>“GAUXTDEE”

字符串中数字的出现是不稳定的,因此我不能依赖诸如 scanf() 之类的函数。

我是 C 编程新手。 感谢您的帮助。

【问题讨论】:

标签: c string numbers strip digit


【解决方案1】:

我会给你一些提示:

  • 您需要创建一个新字符串。
  • 迭代原始字符串。
  • 检查当前字符是否在ascii values of numbers之间
  • 如果没有,请将其添加到新字符串中。

【讨论】:

  • 不要假设ASCII,使用isdigit
  • @Anton 如果您想在编码中获得更多乐趣,您可以尝试将剥离后的字符串版本保存在原始字符串中。
【解决方案2】:
char stringToStrip[128];
char stripped[128];
strcpy(stringToStrip,"GA1UXT4D9EE1");

const int stringLen = strlen(stringToStrip);
int j = 0;
char currentChar;

for( int i = 0; i < stringLen; ++i ) {
    currentChar = stringToStrip[i];
    if ((currentChar < '0') || (currentChar > '9')) {
        stripped[j++] = currentChar;
    }
}

stripped[j] = '\0';

【讨论】:

    【解决方案3】:

    遍历字符串并检查 ascii 值。

    for(i = 0; i < strlen(str); i++)
    {
      if(str[i] >= 48 && str[i] <= 57)
      {
        // do something
      }
    }
    

    【讨论】:

    • 我不建议使用裸数字。最好使用适当的字符常量:if (str[i] &gt;='0' &amp;&amp; str[i] &lt;= '9')... 或者,#include &lt;ctype.h&gt; 并使用 isdigit() 宏。
    【解决方案4】:

    我同意走过去是一种简单的方法,但也有更简单的功能。您可以使用 isdigit()。 C++ 文档有一个很棒的例子。 (别担心,这也适用于 c。)

    http://www.cplusplus.com/reference/cctype/isdigit/

    【解决方案5】:

    这是执行此操作的代码。

    int i;
    int strLength = strlen(OriginalString);
    int resultPosCtr = 0;
    
    char *result = malloc(sizeof(char) * strLength);//Allocates room for string. 
    
    for(i = 0; i < strLength; i++){
        if(!isdigit(OriginalString[i])){
             result[resultPosCtr] = OriginalString[i];
             resultPosCtr++;
        }
    }
    result[resultPosCtr++] = '\0'; //This line adds the sentinel value A.K.A the NULL Value that marks the end of a c style string.
    

    每个人都做对了。

    1. 创建一个新的 char[] A.K.A. C 风格的字符串。
    2. 遍历原始字符串
    3. 检查该迭代中的字符是否为数字
    4. 如果不添加到新字符串中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-28
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多