سؤال

I'm looking for a simple solution for stripping numbers from a string. Example: "GA1UXT4D9EE1" => "GAUXTDEE"

The occurrence of the numbers inside the string is erratic hence I cannot rely on functions such as scanf().

I'm new at programming in C. Thanks for any help.

هل كانت مفيدة؟

المحلول 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';

نصائح أخرى

I will give you some tips:

  • You need to creat a new string.
  • Iterat over the original string.
  • Check if the current character is between the ascii values of numbers
  • If not, add it to the new string.

iterate through the string and check for the ascii value.

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

I would agree that walking through would be an easy way to do it, but there is also an easier function to do this. You can use isdigit(). C++ documentation has an awesome example. (Don't worry, this also works in c.)

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

Here is the code to do it.

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.

Everyone has it right.

  1. Create a new char[] A.K.A. C style string.
  2. Iterate over the original string
  3. Check to see if the character at that iteration is a number
  4. if not add to new string
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top