Programming Examples - Strings | Learn to Program with C++: Beginner to Expert - Back-End Programming PDF Download

Example 1: C++ program to Find Length of String
String Length is the number of character in the given String. For Example: String="India" this word have 5 characters also this is the size of string.
Program 1: Find Length of String Without Using Library function

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
 void main()
{
int i,count=0;
char ch[20];
clrscr();
cout<<"Enter any string: ";
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
count++;
}
cout<<"String Length: "<<count;
getch();
}
Output
Enter any String: hitesh
String Length: 6

Explanation of Code
Here gets() is a predefined function in "conio.h" header file, It receive a set of character or String from keyboard.
Example

for(i=0;ch[i]!='\0';i++)
{
count++;
}

Here we check the condition ch[i]!='\0' its means loop perform until string is not null, when it null loop will be terminate.
Program 2: Find Length of String Using Library Function

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20];
int length;
cout<<"Enter any string: ";
gets(str);
length = strlen(str);
cout<<"String Length: "<<length;
return 0;
}

Output
Enter any String: Kumar
String Length: 5

Explanation of Code
Here gets() is a predefined function in "conio.h" header file, It receive a set of character or String from keyboard.
strlen() is a predefined function in "conio.h" header file which return length of any string.

Example 2: C++ Program to Compare Two Strings
To compare any two string first we need to find length of each string and then compare both strings. If both string have same length then compare character by character of each string.
To understand below example, you have must knowledge of following C++ programming topics;
For Loop in C++, While Loop in C++, String in C++ and Array in C++
Program: Compare two strings in C++

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20],i,j,flag=0;
clrscr();
cout<<"Enter first string: ";
gets(str1);
cout<<"Enter Second string: ";
gets(str2);
i=0;
j=0;
while(str1[i]!='\0')
{
i++;
}
while(str2[j]!='\0')
{
j++;
}
if(i!=j)
{
flag=0;
}
else
{
for(i=0,j=0;str1[i]!='\0',str2[j]!='\0';i++,j++)
{
if(str1[i]==str2[j])
{
flag=1;
}
}
}
if(flag==0)
{
cout<<"Strings are not equal";
}
else
{
cout<<"Strings are equal";
}
getch();
}
Output
Enter First String : rajess
Enter Second String : rajesh
Strings are not equal


Example 3: C++ Program to Reverse a String
Reverse of String means reverse the position of all character of any String. For example reverse of porter is retrop
Program: Reverse a String in C++

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[100],temp;
int i,j=0;
clrscr();
cout<<"Enter any the string :";
gets(str);  //  gets function for input string
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse string is: "<<str;
getch();
}
Output
Enter any the string  : hitesh
Reverse string is : hsetih

Explanation Of Program :
Firstly find the length of the string using library function strlen().
Code
j = strlen(str)-1;
Suppose we accepted String "hitesh" then
Code

j = strlen(str)-1;
= strlen("hitesh") - 1
= 7 - 1
= 6

As we know String is character array and Character array have character range between 0 to length-1. Thus we have position of last character in variable 'j'.Current Values of 'i' and 'j' are :
Code

i = 0;
j = 6;

'i' positioned on first character and 'j' positioned on last character. Now we are swapping characters at position 'i' and 'j'. After interchanging characters we are incrementing value of 'i' and decrementing value of 'j'.
Code

while(i<j)
{
temp   = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}

If i crosses j then process of interchanging character is stopped.

Example 4: C++ program to Count Frequency of Characters
Frequency of character in any string means how many times a particular character is present in any string. For example; suppose we have string hitesh in this word h repeated 2 times, it is the frequency of h in string hitesh.
Program: Count Frequency of Characters in C++

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int i,count=0;
char ch[20],c;
clrscr();
cout<<"Enter Any String: ";
gets(ch);
cout<<"Enter any Character form string: ";
cin>>c;
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]==c)
count++;
}
if(count==0)
{
cout<<"Given character not found";
}
else
{
cout<<"Repetition of " <<c<<" "<<count<<" times";
}
getch();
}
Output
Enter any String: india
Enter any Character form string: i
Repetition of i 2 times


Example 5: C++ program to concatenate two string
Combined two string or Concatenate two string means add both string with each other, we can perform this operation using library function or without library function. For example if first string is john and second string is porter then after combined these string output will be johnporter.
Program: C++ program to concatenate two strings

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char *ch1="john";
char *ch2="porter";
char *ptr;
clrscr();
cout<<"1 st String: "<<ch1;
cout<<"\n 2 nd String: "<<ch2;
strcat(ch1,ch2);
cout<<"\nCombined string is: "<<ch1;
getch();
}
Output
1 st String: john
2 nd String: porter
Combined string is: johnporter


Example 6: C++ Program to Copy One String into Another String
There are two way to copy one sting into another string in C++ programming language, first using pre-defined library function strcpy() and other is without using any library function.
Program 1: Using Library Function

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[10], s2[10];
clrscr();
cout<<"Enter string s1: ";
cin>>s1;
strcpy(s2, s1);
cout<<"String s2: "<<s2;
getch();
}
Output
Enter string s1: Kumar
String s2: Kumar

Program 2: Without Using Library Functions

#include<iostream.h>
#include<conio.h>
int main()
{
char s1[100], s2[100], i;
clrscr();
cout<<"Enter string s1: ";
cin>>s1;
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
cout<<"String s2: "<<s2;
getch();
}
Output
Enter string s1 : Kumar
String s2: Kumar

Explanation of Code

for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}

In the above code first we check string first is not null and after that we initialize one by one elements of first string into second string.

Example 7: C++ Program to Count Number of vowels in String
Program :C++ Program to Find Number of vowels in string

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
int main()
{
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
clrscr();
cout<<"Enter a line of string:\n";
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&& line[i]<='9')
++d;
else if (line[i]==' ')
++s;
}
cout<<"Vowels: "<<v;
cout<<"\nConsonants: "<<c;
cout<<"\nDigits: "<<d;
cout<<"\nWhite spaces: "<<s;
getch();
}
Output
Enter a line of string: This is 5 C program
vowels: 4
Consonants: 9
Digits: 1
White spaces: 4


Example 8: C++ Program to Delete Vowels from Given String
To delete all the vowels (i.e., a, A, e, E, i, I, o, O, u, U) from the string in C++ program. In case of english alphabet their are 5 lower case letter and 5 captipal letter, in this programming code we remove all small as well as capital letter from given string. You can also see this code in C Programming Language, C Program to Delete Vowels from Given String
Program : C++ Program to Delete Vowels from Given String

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
int len, i, j;
clrscr();
cout<<"Please Enter any String: ";
gets(str);
len=strlen(str);
for(i=0; i<len; i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U')
{
for(j=i; j<len; j++)
{
str[j]=str[j+1];
}
len--;
}
}
cout<<"After Deleting the vowels, the String is:"<<str;
getch();
}
Output
Please Enter any String: Hitesh Kumar
After Deleting the vowels, the String is: Htsh Kmr
Output
Please Enter any String: Reetu
After Deleting the vowels, the String is: Rt


Example 9: C++ Program to Find Number of Words in Given Sentence
To Find Number of Words in Given Sentence in C++ program we need to enter any Sentence for user side. After enter sentence count total number of words present in the given string, next search for spaces, if found any space then increase a variable say countword by 1 and continue to check for next space.
To understand below example, you have must knowledge of following C++ programming topics; For Loop in C++, Cin Function in C++ and Cout Function in C++.
Program: Count Word in Given Sentence Program in C++

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
clrscr();
char strs[100], countword=0, strword[15];
int i, len;
cout<<"Write any Sentence: ";
gets(strs);
len=strlen(strs);
for(i=0; i<len; i++)
{
if(strs[i]==' ')
{
countword++;
}
}
cout<<"Total Number of words in Given Sentence is: "<<countword+1;
getch();
}
Output
Write any Sentence: Hitesh Kumar
Total Number of words in Given Sentence is: 2


Example 10: C++ Program to Delete Words from Sentence
For write this program, we first take a sentence as input from user using cin. Then we ask user to enter word for deletion.
To understand below example, you have must knowledge of following C++ programming topics; For Loop in C++, Array in C++ and if else in C++
Example

Input : I love Sitesbay Tutorial
Word to Remove : Sitesbay
Output : I love Tutorial

Program: Delete Words from Sentence Program in C++

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
clrscr();
int i, j = 0, k = 0;
char str[100], str1[10][20], word[20];
cout<<"Enter Any String: ";
gets(str);
for (i=0; str[i]!='\0'; i++)
{
if (str[i]==' ')
{
str1[k][j] = '\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
j++;
}
}
str1[k][j] = '\0';
cout<<"Enter any word to delete: ";
cin>>word;
/* Here Comparing string with the given word */
for (i=0; i<k+1; i++)
{
if (strcmp(str1[i], word) == 0)
{
for (j=i; j<k+1; j++)
{
strcpy(str1[j], str1[j + 1]);
k--;
}
}
}
cout<<"New String After deleting entered word: ";
for (i=0; i<k+1; i++)
{
cout<<str1[i]<<" ";
}
getch();
}
Output
Enter Any String: This is my first C++ Program
Enter any word to delete: first
New String After deleting entered word: This is my C++ Program


Example 11: Swap Two Strings Program in C++
To swap two strings in C++, We need to take two string from user side and store both the string in variables say str1 (string 1) and str2 (string 2).
To swap two strings in C++ Program we need strcpy() function. Here we receive two string from user side and swap these two strings.
To understand below example, you have must knowledge of following C++ programming topics; String in C++ and Array in C++.
Program 1: C++ Program to Swap Two Strings using Third Variable

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char str1[30],str2[30],temp[30];
cout<<"Enter String String 1: ";
cin>>str1;
cout<<"Enter String String 2: ";
cin>>str2;
strcpy(temp,str1);
strcpy(str1,str2);
strcpy(str2,temp);
cout<<"After Swapping  Strings are: "<<endl;
cout<<"String 1: "<<str1;
cout<<endl<<"String 2: "<<str2;
getch();
}
Output
Enter String String 1: Hello
Enter String String 2: Coder
After Swapping  Strings are:
String 1: Coder
String 2: Hello

Swap Two Strings in C++
Program 2: C++ Program to Swap Two Strings

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
int i;
char str1[30],str2[30],temp[30];
clrscr();
cout<<"Enter String String 1 : ";
cin>>str1;
cout<<"Enter String String 2 : ";
cin>>str2;
for(i=0;(temp[i]=str1[i])!=0;i++);
for(i=0;(str1[i]=str2[i])!=0;i++);
for(i=0;(str2[i]=temp[i])!=0;i++);
cout<<"After Swapping Strings Are: "<<endl;
cout<<"String 1 : "<<str1;
cout<<endl<<"String 2 : "<<str2;
getch();
}
Output
Enter String String 1: Hitesh
Enter String String 2: Kumar
After Swapping  Strings are:
String 1: Kumar
String 2: Hitesh


Example 12: C++ Program to Remove Spaces from String or Sentence
To wire this code we need to ask user for enter any sentense. Next we start checking space If space will be found, then start placing the next character from the space to the back until the last character and continue to check for next space to remove all the spaces present in the string.
We will not modify original string instead we will create a new string having all characters of input string except spaces.
Examples To Remove Spaces from a String in C++
Example

Input: Hitesh Kumar
Output: HiteshKumar

Program Execution

  • The program takes a sentence and stores in 'str' array.
  • Using a for loop, if a space is encountered it is removed by shifting elements to the left.
  • The resultant string is printed.

To understand below example, you have must knowledge of following C++ programming topics; String in C++, for remove space here we use For Loop in C++ and Array in C++.

Example of Code

Enter Any String: Sitesbay Make Easy Learning
String After Removing Spaces: SitesbayMakeEasyLearning

Program 1: C++ Program to Swap Two Strings using Third Variable

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
clrscr();
char str[80];
int i=0, len, j;
cout<<"Enter Any String: ";
gets(str);
len=strlen(str);
for(i=0; i<len; i++)
{
if(str[i]==' ')
{
for(j=i; j<len; j++)
{
str[j]=str[j+1];
}
len--;
}
}
cout<<"String After Removing Spaces: "<<str;
getch();
}
Output
Enter Any String: This is my Fist Code
String After Removing Spaces: ThisismyFirstCode

Program 2: Remove Spaces from a String in C++

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char input[100], output[100];
int i, j;
cout<<"Enter any string \n";
cin.getline(input, 500);
for(i = 0, j = 0; input[i] != '\0'; i++)
{
if(input[i] != ' ')
{
// If current character is not a space character,
// copy it to output String
output[j++] = input[i];
}
}
output[j] = '\0';
cout<<"Input String are: "<<input<<endl;
cout<<"String without spaces: "<<output;
getch();
}
Output
Input String are: Hitesh Kumar
String without spaces: HiteshKumar


Example 13: C++ Program to Sort String
To sort strings in C++, We need to take two string from user side and sort them on the basis of alphabets.
Examples to Sort any String in C++
Here you can see first we enter any five name and sort these name according to alphabet.
Example

Faiz
Komal
Akash
Shriniwaslu
Harry
Names After Sort Alphabetical Order are:
Akash
Faiz
Komal
Harry
Shriniwaslu

To understand below example, you have must knowledge of following C++ programming topics; String in C++, for looping statements we need know For Loop in C++ and Array in C++.
Program :C++ Program to Sort String

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char str[5][20], t[20];
int i, j;
cout<<"Please Enter Any Five Name: ";
for(i=0; i<5; i++)
{
cin>>str[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(str[j-1], str[j])>0)
{
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"Names in Alphabetical Order are: \n";
for(i=0; i<5; i++)
{
cout<<str[i]<<"\n";
}
getch();
}
Output
Please Enter Any Five Name: Gaurav
Varsha
Sultan
Uma
Reetu
Names in Alphabetical Order are:
Gaurav
Reetu
Sultan
Uma
Varsha

The document Programming Examples - Strings | Learn to Program with C++: Beginner to Expert - Back-End Programming is a part of the Back-End Programming Course Learn to Program with C++: Beginner to Expert.
All you need of Back-End Programming at this link: Back-End Programming
73 videos|7 docs|23 tests

FAQs on Programming Examples - Strings - Learn to Program with C++: Beginner to Expert - Back-End Programming

1. What is string manipulation in back-end programming?
Ans. String manipulation in back-end programming refers to the process of modifying or manipulating strings (sequences of characters) to achieve a desired outcome. It involves tasks such as concatenation, reversing, searching, replacing, and splitting strings.
2. How can I concatenate two strings in back-end programming?
Ans. In back-end programming, you can concatenate two strings by using the + operator or by using string interpolation. For example, in JavaScript, you can concatenate two strings like this: `var result = string1 + string2;` or using string interpolation: `var result = `${string1}${string2}`;`
3. How do I reverse a string in back-end programming?
Ans. To reverse a string in back-end programming, you can use various techniques. One common approach is to convert the string into an array of characters, reverse the array, and then convert it back to a string. For example, in Python, you can reverse a string like this: `reversed_string = string[::-1];`
4. How can I search for a specific word in a string in back-end programming?
Ans. In back-end programming, you can search for a specific word in a string by using string methods or regular expressions. For example, in Java, you can use the `contains()` method to check if a string contains a specific word: `boolean containsWord = string.contains("word");` Alternatively, you can use regular expressions to perform more complex search patterns.
5. How do I replace a substring in a string in back-end programming?
Ans. To replace a substring in a string in back-end programming, you can use string methods or regular expressions. For example, in PHP, you can use the `str_replace()` function to replace a substring: `newString = str_replace("old", "new", originalString);` This will replace all occurrences of "old" with "new" in the original string.
73 videos|7 docs|23 tests
Download as PDF
Explore Courses for Back-End Programming exam
Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Free

,

Objective type Questions

,

Extra Questions

,

Viva Questions

,

pdf

,

Semester Notes

,

Sample Paper

,

Important questions

,

Summary

,

study material

,

Programming Examples - Strings | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

past year papers

,

video lectures

,

ppt

,

MCQs

,

mock tests for examination

,

shortcuts and tricks

,

Programming Examples - Strings | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Previous Year Questions with Solutions

,

Programming Examples - Strings | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Exam

,

practice quizzes

;