C Strings
char
name[]
=
"John";
String Declaration
Declaring a string is equivalent to declaring a one-dimensional array.
Syntax:
char
string_name[string_size];
Example:
#include
<stdio.h>
int
main
()
{
char
str1[]
=
"Tutorials4Coding";
printf("%s", str1);
return
0;
}
Output
Tutorials4Coding
Access Strings
To change the value of a specific element, use the index number.
Example:
#include
<stdio.h>
int
main
()
{
char
str1[]
=
"Tutorials4Coding";
printf("%c", str1[2]);
return
0;
}
Output
t
String Functions
String functions are a set of functions provided by the C standard library for string manipulation in C
programming.
Let us learn these functions step by step.
strlen():
This function returns the number of characters available in a string.
Example:
#include
<stdio.h>
int
main
()
{
char
str1[]
=
"Tutorials4Coding";
printf("%d", strlen(str1));
return
0;
}
Output
16
strcpy():
This function copies the content of one string into another.
Example:
#include
<stdio.h>
#include
<string.h>
int
main
()
{
char
str1[20]
=
"C Programming";
char
str2[20];
strcpy(str2, str1);
printf("%s", str2);
return
0;
}
Output
C Programming
strcat():
This operation concatenates the source string to the end of the target string. For instance, "Hello" and "Coders" on concatenation would yield a string "HelloCoders".
Example:
#include
<stdio.h>
#include
<string.h>
int
main
()
{
char
str1[20]
=
"Hello ";
char
str2[]
=
"Coders";
strcat(str1, str2);
printf("%s", str1);
return
0;
}
Output
Hello Coders
strcmp():
This operation compares two strings to determine if they are the same or not.
Example:
#include
<stdio.h>
#include
<string.h>
int
main
()
{
char
str1[]
=
"John";
char
str2[]
=
"Harry";
printf("%d", strcmp(str1, str2));
return
0;
}
Output
2