C String end
String end character
ASCII code for the NULL character is \0
.
Example 1
The following code assigns a string ending character to the char array element.
#include <stdio.h>
/*from w w w . j a va2s. c o m*/
int main(){
char myname[4];
myname[0] = 'D';
myname[1] = 'a';
myname[2] = 'n';
myname[3] = '\0';
printf("%s \n",myname);
}
The code above generates the following result.
Example 2
Displaying a string with a string terminator in the middle.
#include <stdio.h>
//ww w. ja va 2 s. c o m
int main(void)
{
printf("The character \0 is used to terminate a string.");
return 0;
}
The code above generates the following result.
Example 3
By setting first[4] to NULL ('\0'), we can shorten the string
#include <string.h>
#include <stdio.h>
/*from w w w . jav a 2s .c om*/
int main()
{
char name[30];
strcpy(name, "Saaaaaaaaaaaaaaam");
printf("The name is %s\n", name);
name[4] = '\0';
printf("The name is %s\n", name);
return (0);
}
The code above generates the following result.
Example 4
Overwrite the newline character in string
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* ww w.j a v a 2 s. co m*/
int main(void)
{
char text[100];
printf("\nEnter the string to be searched(less than 100 characters):\n");
fgets(text, sizeof(text), stdin);
text[strlen(text)-1] = '\0';
printf("%s",text);
}
The code above generates the following result.