2013-07-09 34 views
1

我正在尋找一種簡單的方法來從字符串中去除數字。 例如:「GA1UXT4D9EE1」=>「GAUXTDEE」從C中的字符串中去除數字

字符串中數字的出現是不穩定的,因此我不能依賴諸如scanf()之類的函數。

我是C編程新手。 感謝您的幫助。

+2

那你試試? – ouah

+0

C中沒有簡單的字符串操作解決方案:p 發佈您的代碼! –

+0

這可能有助於http://stackoverflow.com/questions/8044081/how-to-do-regex-string-replacements-in-pure-c – Seano666

回答

1
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'; 
1

遍歷字符串並檢查ascii值。

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

我不建議使用裸數字。最好使用適當的字符常量:'if(str [i]> ='0'&& str [i] <='9')'...或者'#include '並使用'isdigit()宏。 –

3

我會給你一些提示:

  • 你需要創造一個新的字符串。
  • Iterat覆蓋原始字符串。
  • 檢查當前字符是否在ascii values of numbers
  • 如果不是,請將其添加到新字符串中。
+1

不要假設ASCII,使用['isdigit'](http://www.cplusplus.com/reference/cctype/isdigit/) – Kninnug

+0

@Anton如果你想讓編碼更有趣,你可以嘗試保存已刪除的版本原始字符串中的字符串。 –

0

我會同意,通過行走將是一個簡單的方法來做到這一點,但也有一個更簡單的功能做到這一點。你可以使用isdigit()。 C++文檔有一個很好的例子。 (別擔心,這也適用於角)

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

+0

[http://pubs.opengroup.org/onlinepubs/9699919799/functions/isdigit.html](http://pubs.opengroup.org/onlinepubs/9699919799/functions/isdigit.html) –

0

下面是代碼來做到這一點。

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. 創建一個新的字符[] A.K.A. C風格的字符串。
  2. 遍歷原始字符串
  3. 檢查,看看是否在該次迭代的字符是數字
  4. 如果不增加新的字符串