0

This should be relatively simple. I've got a string/character pointer that looks like this

" 1001"

Notice the space before the 1. How do I remove this space while still retaining the integer after it (not converting to characters or something)?

Zack
  • 13,454
  • 24
  • 75
  • 113
  • There are some related answers worth looking at here: http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way http://stackoverflow.com/questions/7775138/strip-whitespace-from-a-string-in-place – poundifdef Dec 12 '13 at 00:58
  • 1
    Don't quite understand what you're asking. Do you want to convert a string to binary, or leave it a string and remove spaces? – Fiddling Bits Dec 12 '13 at 00:58

5 Answers5

1

The simplest answer is:

char *str = " 1001";
char *p = str+1; // this is what you need
mb84
  • 683
  • 1
  • 4
  • 13
1

If the space is at the beginning of string.You also can do it.

char *str = " 1001";
char c[5];
sscanf(str,"%s",c);
printf("%s\n",c);

%s will ignore the first space at the beginning of the buffer.

qdd
  • 61
  • 3
0

One solution to this is found here: How to remove all occurrences of a given character from string in C?

I recommend removing the empty space character or any character by creating a new string with the characters you want.

You don't seem to be allocating memory so you don't have to worry about letting the old string die.

Community
  • 1
  • 1
visc
  • 4,794
  • 6
  • 32
  • 58
0

If it is a character pointer, I believe

char* new = &(old++);

Should do the trick

0

I'm guessing your reading in a String representation of an integer from stdin and want to get rid of the white space? If you can't use the other tricks above with pointers and actually need to modify the memory, use the following functions.

You can also use sprintf to get the job done.

I'm sure there is more efficient ways to trim the string. Here is just an example.

void trim(unsigned char * str)
{
  trim_front(str);
  trim_back(str);
}

void trim_front(unsigned char * str)
{
  int i = 0;
  int index = 0;
  int length = strlen(str);

  while(index < length && (str[index] == ' ' || str[index] == '\t' || str[index] == '\n'))
  {
    index++;
  }

  while(index < length)
  {
    str[i] = str[index];
    i++;
    index++;
  }
}

void trim_back(unsigned char * str)
{
  int i;

  for(i = 0; str[i] != ' ' && str[i] != '\n' && str[i] != '\t' && str[i] != '\0'; i++);

  str[i] = '\0';
}
slowmo
  • 81
  • 7