3

I am doing a program in C, and currently I'm having problems. I don't know how to remove the last part of the string. For example:

char str[100] = "one => two";

I want to remove => two. Can you help me? Thanks in advance.

1
  • Can you give us more examples so we can find a one-size-fits-all solution?
    – rgajrawala
    Mar 2, 2015 at 5:05

4 Answers 4

4

If you want to remove the part after a particular char token then use:

char str[100] = "one => two";
char *temp;
temp = strchr(str,'=');   //Get the pointer to char token
*temp = '\0';             //Replace token with null char
0
1

In C, the string's end is marked with a zero character. Thus, you can remove the end of the string by writing a zero in the correct position:

str[3] = 0;
1

find the place of the blank right after "one" and replace it with a '\0'

0
0

If the first part of your string always ends before the "=" and assuming it will always have the "=", you could do this:

int i = 0; 
char newstr [100];
while (str[i] != '='){
    i++;
}
strncpy (newstr,  str, i); //copy the i first characters from a char [] to a new char []
newstr [i] = 0;

Remember to include string.h to use strncpy

1
  • @rpattiso, I edited to fix the backwards problem and added a null byte at the end of the string. Thanks for pointing them out! Mar 2, 2015 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.