Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip first and last character from C string

I have a C string that looks like "Nmy stringP", where N and P can be any character. How can I edit it into "my string" in C?

like image 684
igul222 Avatar asked Nov 13 '09 00:11

igul222


People also ask

How do you get rid of the first and last character in a string C?

Removing the first and last character In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0 . In C \0 means the ending of a string.

How do you remove the last character of a string in C?

Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.

How do I return the first and last letter of a string?

To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str. length - 1] returns the last character of the string.

How do you trim first and last characters?

To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str. slice(1, -1) .


1 Answers

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP"; char *p = mystr; p++; /* 'N' is not in `p` */ 

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */ 
like image 92
pmg Avatar answered Oct 04 '22 16:10

pmg