Strings are commonly used data types in C . Strings are also known as Character array as they consists of group of chars.
char name[]={'p','l','u','s','2','n','e','t','\0'};
Declaring a string in C
First position of the string starts with 0. While declaring a string we can specify the number of chars to be used or reserved in memory.
Null char at the end
When we declare a string, C adds one null character ( \0 ) at the end. So we can check for this null character to identify the end of the string.
char name[10]="plus2net";
We can insert one null char ( \0 ) to terminate the string.
char name[10]="plus2net";
name[3]='\0';
printf("%s",name); // plu
Output
plu
We can check for this null character to identify the end of the string.
char name[]="plus2net";
int i=0;
while(name[i]!='\0'){
printf("%c ",name[i]);
i=i+1;
}
Output
p l u s 2 n e t
Basic string assignments »
Sample Codes
Reading and displaying a string.
#include <stdio.h>
int main(void){
char my_name[20];
printf("Enter your name : ");
scanf("%s",my_name);
printf("Welcome %s",my_name);
return 0;
}
Printing string vertically with total number of chars
#include <stdio.h>
int main(void){
int i;
char str[]="Welcome";
for ( i=0;str[i] != '\0';i++){
printf( "%c \n",str[i]);
}
printf("\n Total number of chars = %d",i);
return 0;
}
W
e
l
c
o
m
e
Total number of chars = 7
« C Tutorials