C Language: String Inbuilt Functions

String Inbuilt Functions

String inbuilt functions

 Header file : string.h

 #include<string.h>

strlen() : (String length)

The “strlen()” function gives the length of a string, not including the NULL character at the end. Spaces are included in the length.

syntax:
variable=strlen(string);

N=”HELLO”; 

H

E

L

L

O

‘\0’

Example:
n=”Hello”;
strlen(n);
Ans: 5
n=”Hello world”;
strlen(n);
Ans: 11

#include<stdio.h>
#include<string.h>
int main()
{
	char n[20];
 	int len;
 	printf("Enter any string ");
 	scanf("%s",n);
 	//gets(n);
 	//scanf("%[^\n]s",n);//to input string with space
 	//scanf("%4s",n); //will take input for only first 4 characters
 	printf("string is %s\n",n);
 	len=strlen(n);
 	printf("len = %d\n",len);
 	return(0);
}
/* Output */

Enter any string Hello
string is Hello
len = 5

strcpy() :  (String copy)

This function helps us to the copy the contents of one string onto another string

Syntax:
strcpy(string1,string2);

the content of 2nd string will be copied onto the the 1st string , if string1 is containing some text it will be overwritten.

Example:1
n1=”hello”;
n2=”hi”;
strcpy(n1,n2);
contents of n2 will be copied onto n1
result:
n1=”hi”
n2=”hi”
Example:2
n1=”hello”;
n2=”hi”;
strcpy(n2,n1);
contents of n1 will be copied onto n2
result:
n1=”hello”
n2=”hello”

 #include<stdio.h>
 #include<string.h> 
 void main()
 {
 	char n[20],n1[20];
 	printf("Enter any string ");
 	gets(n);
 	strcpy(n1,n);
 	printf("String is %s ,copied string is %s\n",n,n1);
 	return(0);
 }
/* Output */

Enter any string hello
String is hello ,copied string is hello

strcat() :(string concatenation/string joining)

This function helps us to add the contents of one string into another string.

Syntax:
strcat(string1,string2);

the content of 2nd string will be added onto the contents of 1st string.

Example:1
n1=”hello”
n2=”hi”
strcat(n1,n2);
contnets of n2 will be added after the existing contents of n1
result:
n1=”hellohi”
n2=”hi”

Example:2
n1=”hello”
n2=”hi”
strcat(n2,n1);
contnets of n1 will be added after the existing contents of n2
n1=”hello”
n2=”hihello”

Example:3
if we want to add two strings in third string
n1=”hello”
n2=”catalyst”
n3
strcpy(n3,n1)
strcat(n3,n2)
result:
n3=”hellocatalyst”

Example:4
if we want to add two strings in third string and give space between them
n1=”hello”
n2=”catalyst”
n3
strcpy(n3,n1)
strcat(n3,” “);
strcat(n3,n2)
result:
n3=”hello catalyst”

#include<stdio.h>
#include<string.h>
int main()
{
	char n1[20],n2[20],n3[40];
	printf("Enter 1st string ");
 	gets(n1);
 	printf("Enter 2nd string ");
 	gets(n2);
 	strcpy(n3,n1);
 	strcat(n3," ");//for space
 	strcat(n3,n2);
 	printf("concatenated string is %s\n",n3);
 	return(0);
}
/* Output */

Enter 1st string Hello
Enter 2nd string World
concatenated string is Hello World