dharag
dharag

Reputation: 299

trim char array C++

How do i trim a char array ?

I'm reading this array from the text file and when it matches a certain string , ive to process it. But it never matches. I assume because it contains some trailing and leading spaces or\and '\n'

I dont know how to trim a char array but i used this to removes spaces. This has a problem that when token[0] = {0 0 0 0} this makes it {0000}. So i dont know what to do next..

char a[50] = {0};
int j = 0;

    //Removing spaces or garbage values in token[0] for perfect string match
    for(int i=0; (unsigned)i<strlen(token[0]) ; ++i )
    {
      if( (isalnum(token[0][i])) || token[0][i] == 95)
      {
        a[j]=token[0][i];
        j++;
      }
      else
      {
        continue;
      }
    }

Upvotes: 0

Views: 10477

Answers (1)

Shikher Gupta
Shikher Gupta

Reputation: 31

Given that you have not mentioned anything else, the following could always be done:

copy the array(to be checked) to another array char by char to only the number of chars required...(this way you could also check how many chars you need to trim):

a=0;

while(array1[a] != '\0'){
    array2[a] = array1[a];
    a++;
}

array2[a] = '\0';

Upvotes: 3

Related Questions