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?
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.
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.
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.
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) .
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) */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With