Strings in C
Strings in C
char string_name[size];
C String Initialization
C String Example
#include <stdio.h>
#include <string.h>
int main()
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
return 0;
Output
Geeks
#include<stdio.h>
int main()
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
Input
GeeksforGeeks
Output
GeeksforGeeks
You can see in the above program that the string can also be
read using a single scanf statement. Also, you might be
thinking that why we have not used the ‘&’ sign with the
string name ‘str’ in scanf statement! To understand this you
will have to recall your knowledge of scanf.
We know that the ‘&’ sign is used to provide the address of
the variable to the scanf() function to store the value read in
memory. As str[] is a character array so using str without
braces ‘[‘ and ‘]’ will give the base address of this string.
That’s why we have not used ‘&’ in this case as we are
already providing the base address of the string to scanf.
// whitespaces
#include <stdio.h>
// driver code
int main()
char str[20];
// taking input string
scanf("%s", str);
printf("%s", str);
return 0;
Input
Output
Geeks
// C program to illustrate
// fgets()
#include <stdio.h>
#define MAX 50
int main()
char str[MAX];
puts(str);
return 0;
Input
GeeksforGeeks
Output
String is:
GeeksforGeeks
// scanset characters
#include <stdio.h>
// driver code
int main()
{
char str[20];
scanf("%[^\n]s", str);
printf("%s", str);
return 0;
Input
Output
C String Length
#include <stdio.h>
int main()
// to a different function
printStr(str);
return 0;
}
Output:
String is : GeeksforGeeks
#include <stdio.h>
int main()
printf("%c", *ptr);
ptr++;
return 0;
Output
GeeksforGeeks
strlen() function in c
Syntax of C strlen()
Parameters
Return Value
This function returns the integral length of the string
passed.
C strlen() Function
Example of C strlen()
C
// c program to demonstrate
#include <stdio.h>
#include <string.h>
int main()
// defining string
return 0;
Output
Length of string is : 13