Removing null terminator at the end of the string

Im trying to scan a character from input , i have tried all method , scanf() getline() fgets() but all contains null terminator '\0' at the end which is unwanted for me . How can i strip it? I have tried

char *p=strtok(string,'\0\') 

but it didnt work. How can i do it? I am scanning strings usgin getline() into an array of string , which works fine and i want to input an "needle" which i am trying to scanf with getline() too and than use strstr to find match but '\0' is causing no match

asked Dec 7, 2015 at 21:04 87 1 1 gold badge 1 1 silver badge 7 7 bronze badges What are you trying to achieve? Commented Dec 7, 2015 at 21:05

Generally, you should not remove the null terminating character from a string. If you do and you pass the string to any of the functions in string.h(and some functions in other libraries as well), the program will crash.

Commented Dec 7, 2015 at 21:09

i need it to strip it bcs i am want to use this string as needle in strstr() and with '\0' it only matches the end of the string

Commented Dec 7, 2015 at 21:12

strstr requires both arguments to be NULL-terminated strings, so you shouldn't do that. Please post a Minimal, Complete, Verifiable Example that illustrates the problem and your attempt at it.

Commented Dec 7, 2015 at 21:14

You should explain your other problem because I think you're trying to fix it incorrectly. When using strings in C, the null terminator is required in order to know where the end of the string is.

Commented Dec 7, 2015 at 21:18

3 Answers 3

You asked how to remove the NUL terminator from the end of a string. You can do that by overwriting it with something else (say, the letter 'a'):

str[strlen(str)] = 'a'; 

Note that C does not have a way to "remove" something from an array (including a string, which is an array of char s); array elements always exist (until the whole array is destroyed), and they can only be overwritten with other values.

answered Dec 7, 2015 at 21:45 58.7k 7 7 gold badges 53 53 silver badges 98 98 bronze badges

C uses null-terminated strings which means that all library functions that are intended to work with "strings" will give you and expect to be given an array of characters follow by a null terminator.

You can copy all the bytes from the string except the null terminator into a new char array:

char buffer[strlen(string)]; memcpy(buffer, string, strlen(string)); p* = buffer; 

Note: strlen doesn't include the null terminating character in the character count

But if you pass p* as parameter to a function that expects a string then expect problems at runtime. You've been warned :)