Understanding Strings in C Programming
Understanding Strings in C Programming
3.6 Strings:
String is sequence of characters i.e letters, numbers and symbols and punctuation marks.
The string in C programming language is actually a one-dimensional array of characters which is
terminated by a null character '\0'. Since string is an array, the declaration of a string is the same as
declaring a char array. Characters are enclosed in single quotes(‘ ‘) and strings are enclosed in double
quotes(“ “).
Syntax:
Data_type variable_name[size];
Char variable_name[size];
You should not specify the datatype because string only char datatype.
char str1[20];
char str2[7] = “String”;
The following declaration creates string named “str2” and initialized with value “String”. To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word.
Note: The C compiler automatically places the '\0' at the end of the string when it initializes the array.
The terminating null (‘\0’) is important, because it is the only way the functions that work with a string
can know where the string ends.
msg
5000
OUTPUT : OUTPUT:
Ramesh Ramesh
Note:
To read and write string elements we need formatting specifier %s. here no need to use iterators
(loops).
Generally, to read input from the keyboard we provide & (address operator) but to read string
we need not provide & operator because the string variable always holds the base address only,
The compiler automatically collect the all characters one by one.
Example :
#include <stdio.h>
void main( ) Beginning of End of String End of Character
{ the string array
char name[7];
printf(“enter your name); 0 1 2 3 4 5 6
scanf(“%s”,name);
printf(“\n Hi %s ,Welcome to R a m \0 \0 \0 \0
CSE”,name);
name 124 125 126 127 128 129 130
}
124
Base adreess Compiler automatically
OUTPUT: Stores the all the char of the
Enter your name: Ram String in successive memory
Hi Ram, Welcome to CSE Locations.
Cmd prompt:
When the compiler assigns a character string to a character array, it automatically appends null
character to end of string .The size of string should be equal to maximum no of characters in
the string plus one.
In above program, the compiler creates a character array of size 7,stores the “Ram” in it and
finally terminates the value with null character. Rest of the elements in the array are
automatically initialized to NULL.
String Character
1.
char branch[]=”CSE”;
C S E \0
Char ch=’R’;
Beginning of End of
the string String
R
2.
Char str[]=”R”;
Here R is a character not a string.
The character R requires only one
R \0 memory location.
3. Char str[]=””;
Empty string \0
Functions
Read Write
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in the loop in case you
want to read more than one characters.
The putchar() function prints the character passed to it on the screen and returns the same
character. This function puts only single character at a time. In case you want to display more
than one characters, use putchar() method in the loop.
#include <stdio.h>
int main( )
{
int ch;
printf("Enter a character:");
ch=getchar();
putchar(ch);
return 0;
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value,
it will display the value you have entered.
The gets() function reads a line or multiword string from stdin into the buffer pointed to by s
until either a terminating newline or EOF (end of file).
The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: Ramesh M
Hello! Ramesh M
3.7.3 Difference between scanf() and gets() and printf() and puts() :
Note :
The isalpha( ) function returns nonzero if ch is a letter of the alphabet; otherwise zero is
returned.
The isalnum( ) function returns nonzero if its argument is either a letter of the alphabet or a
[Link] the character is not alphanumeric, zero is returned.
The iscntrl( ) function returns nonzero if ch is a control character.
The isdigit( ) function returns nonzero if ch is a digit, that is, 0 through 9. Otherwise zero is
returned.
The ispunct( ) function returns nonzero if ch is a punctuation character; otherwise zero is
returned.
The isspace( ) function returns nonzero if ch is a white-space character, including space,
horizontaltab, vertical tab, formfeed, carriage return, or newline character; otherwise zero is
returned.
The isxdigit( ) function returns nonzero if ch is a hexadecimal digit; otherwise zero is returned
Example:
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("isalpha('a') : %d\n" , isalpha('a'));
printf("isalpha(34) : %d\n" , isalpha(34));
printf("isalnum('A') : %d\n" , isalnum('A') ) ;
printf("isalnum(5) : %d\n" , isalnum(5) );
char ch=’R’;
printf(“enter a character:”);
scanf(“%d”&ch);
printf("iscntrol('R') : %d\n" , iscntrl(ch)) ;
printf("isdigit('9') : %d\n" , isdigit('9'));
printf("isdigit('a') : %d\n" , isdigit('a')) ;
printf("isdigit(9) : %d\n" , isdigit(9)) ;
printf("ispunct('.') : %d\n" , ispunct('.')) ;
printf("ispunct(',') : %d\n" , ispunct(',')) ;
printf("ispunct('c') : %d\n" , ispunct('c')) ;
printf("isspace(' ') : %d\n" , isspace(' ')) ;
printf("isspace('\\t') : %d\n" , isspace('\t'));
printf("isspace('\\r') : %d\n" , isspace('\r')) ;
printf("isxdigit('F') : %d\n" , isxdigit('F')) ;
printf("tolower('A') : %c\n" , tolower('A')) ;
printf("toupper('z') : %c\n" , toupper('z')) ;
return 0;
OUTPUT :
Function Description
strcat() Appends one string at the end of another. And strncat() upto n
strncat() characters.
strcpy() Copies a string into another and copies a string upto n
strncpy() characters
strcmp()
strncmp() Compares two strings and compare upto n numbers.
strchr()
Finds first occurrence of a given character in a string.
The function takes a single argument, i.e, the string variable whose length is to be found, and
returns the length of the string passed.
If destination string length is less than source string, entire source string value won’t be copied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20
characters from source string will be copied into destination string and remaining 10 characters won’t
be copied and will be truncated.
Output
Source string = Nuzvid
Destinnation string = Nuzvid
This function copies up to n characters from [Link] n is zero or negative then nothing is copied.
Syntax for strncpy( ) function is given below.
Output
Source string = Nuzvid
Destinnation string = Nuz
For example, “Visakhapatanam” and “Vizag” on concatenation would result a new string
“VisakhapatnamVizag”.
For example, “Vizag” and “Visakhapatam” on concatenation (upto n Characters) would result a new
string “VizagVisakha”. Here n is 7.
#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] =" Visakhapatnam " ;
char target[30] = "Vizag" ;
strncat ( target, source,7) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Visakhapatnam
Destination string = VizagVisakha
Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
}
Output
0 4 -32
0 -1 1
Output:
n is found string at address position 661863
n is found string at address position 9
Output:
The substring address position at 1636788
The sub string is found !!
int main()
{
char str1[20];
char str2[20];
int count;
printf("Enter String1:");
gets(str1);
printf("Enter String2:");
gets(str2);
count=strspn(str1,str2);
printf("Similar characters occurred upto %d\n",count);
return 0;
}
Output:
Enter String1: Welcome to CSE
Enter String1: Welcome to ECE
Similar characters occurred upto 12.
[Link]. Dept of CSE,IIIT-Nuzivid. Page 13
PSTC UNIT-III Strings
char str[100];
char deli[100];
char *token;
printf("Enter any string with delimiters :");
gets(str);
printf("enter delimiter :");
gets(deli);
token=strtok(str,deli);
while(res!=NULL)
{
printf("\n %s",token);
token=strtok(NULL,deli);
}
Output:
Enter any string with delimiters: ramesh,cse,iiit nuzvid,programming in c
Enter delimiters: ,
ramesh
cse
iiit nuzvid
programming in c
{
if((str[i] >='a' && str[i]<='z')
str[i]=str[i]-32;
}
[Link]. Dept of CSE,IIIT-Nuzivid. Page 15
PSTC UNIT-III Strings
4. Write a program to concatenating two and stores the result in new string.
#include<stdio.h>
int main()
{
char str1[100],str2[100],str3[100];
int i=0,j=0;
printf("\n enter the first string:");
gets(str1);
printf("\n enter the second string: ");
gets(str2);
while(str1[i]!='\0')
{
str3[i]=str1[i]; Output:
i++; enter the first string: Cse
j++; enter the second string : IT
} The Concatenated string is: CseIT
i=0;
while(str2[i]!='\0')
{
str3[j]=str2[i];
i++;
j++;
}
str3[j]='\0';
printf("\n The Concatenated string is :");
puts(str3);
return 0;
}
j++;
}
target[j]='\0';
printf("\n The final target string is :");
puts(target);
return 0;
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50],str2[50];
int i=0,len1=0,len2=0,s=0;
printf("\nEnter the first string:");
gets(str1);
printf("\n Enter second string:");
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
{
while(i<len1)
{
if(str1[i]==str2[i])
i++;
else break;
}
if(i==len1)
{
printf("two strings are equal");
[Link]. Dept of CSE,IIIT-Nuzivid. Page 17
PSTC UNIT-III Strings
s=1;
}
}
if(len1!=len2)
{
printf("\n two strings are not equal");
}
if(s==0)
{
if(str1[i]>str2[i])
printf("\n string 1 is greater than string 2 ");
if(str1[i]<str2[i])
printf("\n string 1 is lessthan than string 2 ");
}
}
Output :
Enter the first string: Cse
Enter the second string : Cse
Two strings are equal
Output :
Enter a string : cse
the reversed string is: esc
8. Write a program to extract the first N characters (Sub String ) of a string from left.
#include<stdio.h>
int main()
{
char str[50];
char sub_str[50];
int i=0,n;
printf("\n Enter a string: ");
gets(str);
printf("\nEnter no of characters to be copied: ");
scanf("%d",&n);
while(str[i]!='\0' && i<n)
Output:
{
Enter a string: Welcome to Cse
sub_str[i]=str[i];
Enter no of characters to be copied :7
i++; The Substring is: Welcome
}
sub_str[i]='\0';
printf("\n The Substring is:");
puts(sub_str);
return 0;
}
9. Write a program to extract the first N characters (Sub String ) of a string from Right.
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char sub_str[50];
int i=0,j=0,n;
printf("\n Enter a string: ");
gets(str);
printf("\nEnter no of characters to be copied: ");
scanf("%d",&n);
j=strlen(str)-n;
while(str[j]!='\0')
Output:
{
Enter a string: Welcome to Cse
sub_str[i]=str[j];
Enter no of characters to be copied :3
i++; The Substring is:Cse
j++;
}
sub_str[i]='\0';
printf("\n The Substring is:");
puts(sub_str);
return 0;
}
10. Write a program to extract the first N characters (Sub String) of a string from middle.
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char sub_str[50];
Output:
Enter a string: Welcome to Cse
Enter the position from to start of sub string: 8
Enter no of characters to be copied :2
The Substring is: to
Syntax :
Example:
char name[4][8]={“Ram”,”IIITN”,”Cse”,”Nuzvid”};
name[0] R a m \0
name[1] I I T N \0
C s e \0
name[2]
name[3] N u z v i d \0
char name[4][8];
while(i<4)
{
printf("\nEnter the student %d name: ",i+1);
gets(name[i]);
i++;
}
printf("\n Names of the students :");
for(i=0;i<4;i++)
{
puts(name[i]);
}
return 0;
}
Output:
Enter the student 1 name : Ram
Enter the student 2 name : Krish
Enter the student 1 name : Sree
Enter the student 2 name : Sai
Names of the students:
Ram
Krish
Sree
Sai