AmperSand
AmperSand

Reputation: 71

How to remove last part of string in c

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.

Upvotes: 3

Views: 9800

Answers (4)

Patrick Sava
Patrick Sava

Reputation: 126

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

Upvotes: 0

Vagish
Vagish

Reputation: 2547

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

Upvotes: 4

Peter Zhu
Peter Zhu

Reputation: 1194

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

Upvotes: 1

jlahd
jlahd

Reputation: 6293

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;

Upvotes: 1

Related Questions