0

Lets see this example:

char var1[100] = "test    ";
char* var2;

If I do this:

var2 = &var1;

I'll get it with spaces.

I want var2 to be the trim of var1.

Richasantos
  • 576
  • 2
  • 8
  • 15

2 Answers2

0

As far as I know there's no way of doing this without changing the original string or copying a modified version of that string to a new source.

As pm100 said, you can find the pointer pointing to the first instance of space in that string, then get the distance from your source pointer and that pointer to find the index of the whitespace. After doing so, simply use strncpy to copy that portion of the string to a new pointer. Make sure you allocate your new pointer and put the terminating character '\0' at the end.

The other solution is to simply use strchr again as pm100 said, but this time change what that pointer points to to '\0'.

SenselessCoder
  • 1,139
  • 12
  • 27
0

a quicky

var2 = strdup(var1);
char * idx = strchr(var2, ' ');
if(idx) *idx = 0;
pm100
  • 48,078
  • 23
  • 82
  • 145