1)Program to perform all the basic string operations is discussed here. Some of the basic operations are printing the string, printing the length of the string, reversing a string, concatenating two strings, and so on.
For example, consider two strings str1 = "Focus" str2 = "Academy"
Length of str1 is 5
Length of str2 is 7
Reverse of str1 is sucoF
Reverse of str2 is ymedacA
Concatenation of str1 and str2 is FocusAcademy
i) String Operations | Program to print a string
/* C++ program to print a string */
#include <iostream> using namespace std; int main() { string a;
int l; cout << “\nEnter the string : “; cin >> a; cout << “The string is ” << a; return 0;
}
Output
Enter the string : Focus
The string is : Focus
ii) String Operations | Program to print the length of a string
/* C++ program to print the length of a string */
#include <iostream> #include <string.h> using namespace std;
int main()
{ char a[100];
int l; cin >> a;
int i; l = strlen(a); cout << “\nThe length of the string is ” << l << endl; return 0;
}
Enter the string : Focus
The length of Focus is 5
iii) String Operations | Program to copy a string
/* C++ program to copy a string */
#include <iostream> #include <string.h> using namespace std;
int main() { char a[100], b[100];
int l; cin >> a; strcpy(b, a); cout << “\String 1 : ” << a << endl << “String 2 : ” << b << endl; return 0;
}
Output
Enter string : Focus
String 1 : Focus
String 2 : Focus
iv) String Operations | Program to reverse a string
/* C program to reverse a string */
#include <iostream> #include <string.h> using namespace std; int main()
{ char a[100];
int l; cin >> a;
int i;
cout << “Reversed String : “; for(i = strlen(a); i >= 0; i–)
{ cout << a[i];
} return 0;
}
Output
Enter the string : Focus
Reversed String : sucoF
v) String Operations | Program to concatenate two strings
/* C++ program to concatenate two strings */
#include <iostream> #include <string.h> using namespace std; int main()
{
char str1[] = “Face “, str2[] = “Prep”; strcat(str1,str2); cout << “After concatenation : “; cout << str1;
return 0;
}
Output
After concatenation : FacePrep
vi) String Operations | Program to compare two strings
/* C++ program to compare two strings */
#include <iostream> #include <string.h> using namespace std; int main()
{ char str1[100], str2[100]; cin >> str1 >> str2; strcmp(str1,str2); if(strcmp(str1,str2) == 0) cout << “The strings are equal”; else cout << “The strings are not equal”; return 0;
}
Output
Enter the string 1 : Focus
Enter the string 2 : Focas
The strings are not equal
2) i) Program to find the length of a string without using strlen() function
// C++ program to find length of a string without using strlen() function
#include <iostream> using namespace std; int main()
{ char s[100];
int i;\ cout << “\nEnter a string: “; cin >> s; for(i = 0; s[i] != ‘\0’; ++i); cout << “\nLength of string : ” << i; cout << endl; return 0;
}
Output
Input- Enter a string: HelloWorld! Output- Length of
string:11
ii) Program to find the length of a string using pointers
// C++ program to find length of a string using pointers
#include <iostream> using namespace std;
int length_of_string(char*p)
{ int count = 0; while (*p != ‘\0’) {
count++; p++;
} return count;
} int main() { char str[50]; int length; cout << “\nEnter any string : “; cin >> str; length = length_of_string(str); cout << “\nThe length of the given string : ” << length; cout << endl; return 0;
}
Output
Input- Enter a string: HelloWorld! Output- Length of string:11
3) Program to toggle each character in a string is discussed here. A string is given as input in which all the lower case letters are converted to upper case and the upper case letters are converted to lower case.
For example, consider the following string
Input: FacePrep
Output: fACEpREP
Input: FocucAcadeMy
Output: fOCUSaCADEmy
// C++ program to toggle each character in a string
#include <iostream>
#include <stdio.h>
using namespace std;
#define MAX_SIZE 100
void toggleCase(char * str);
int main()
{
char str[MAX_SIZE];
cout << “nEnter the string : “; scanf(“%[^n]s”, &str); toggleCase(str); cout << “nReplaced string after toggling characters : “; cout << str << endl; return 0;
} void toggleCase(char * str)
{ while(*str)
{ if(*str >= ‘a’ && *str <= ‘z’)
*str = *str – 32; else if(*str >= ‘A’ && *str <= ‘Z’)
*str = *str + 32;
str++;
}
}
Output
Enter the string : FACEprep
String after the characters are toggled : facePREP
Time complexity: O(n)
ii) by using library function
Program to toggle each character in a string using standard library functions is given below.
// C++ program to toggle each character in a string
#include<iostream.h>
#include<stdio.h>
#include<string.h>
using namespace std;
int main ()
{ char str[50]; cout << “Enter the string : “; gets(str);
for (int i = 0; str[i] !=''; i++)
{
if (isalpha(str[i]))
{
if (islower(str[i]))
str[i] = toupper(str[i]);
else
str[i] = tolower(str[i]);
}
}
cout << “String after toggling each characters : ”<<str;
}
4) Program to display the number of vowels in a given character array
// C++ program to display the count of vowels in a given character array
#include <iostream> using namespace std; int main()
{ char str[100]; // characer array char *ptr; // pointer int cntV,cntC; // variables to store the count of vowels and sonsonants
cout << “Enter a string: “; cin >> str;
ptr=str; // Assign the character array to the pointer
cntV=cntC=0;
while(*ptr!=’\0′) // Check if the scanned character is a vowel
{
if(*ptr==’A’ ||*ptr==’E’ ||*ptr==’I’ ||*ptr==’O’ ||*ptr==’U’ ||*ptr==’a’ ||*ptr==’e’ ||*ptr==’i’
||*ptr==’o’ ||*ptr==’u’) cntV++; // increment vowel count
else cntC++; // increment consonant count ptr++; // Increment the pointer to scan the next character
}
cout << “Total number of vowels : ” << cntV << “\nTotal number of consonants : ” << cntC << endl; return 0;
}
5) In a town, houses are marked with English alphabets. Committee in the town wants to renovate the houses. They decided to renovate only houses named with vowels. Committee has given the list to members and asks them to identify the houses which are not renovated. Write an algorithm to help the committee members to find houses which are not renovated.
● Input: Input to the function contains only one argument.
● House: A string representing the sequence of house markings.
● Output: return a string that represents the houses which were not renovated.
The logic to be used:
The logic behind this question is simple. It is to remove the vowels in the given string and display the input string without vowels (i.e with only consonants).
using namespace std; int check_vowel(char check_character) // To check the vowels
{
{
● Create a new string variable.
● Copy each element of the input string to the new string.
● If anyone of the parenthesis is encountered as an element, don't copy that to the
new string.
OR
● If anyone of the parenthesis is encountered as an element, replace it with(empty
space). This method is very easy in Java and Python.
return 0;
}
int main()
string s;
int j=0;
cout<<“Enter the String:”;
cin>>s;
int len = 0;
while (s[len])
len++;
char t[len];
for(int i=0; i< len; i++)
int temp = remove_brackets(s[i]);
(temp == 0)
t[j] += s[i];
j++;
cout<<t;
return 0;
{
{
if
{
}
}
}
for(j = i; input[j] != ‘\0’; ++j)
Input 1 :
Hello All. Welcome to Face
Output 1:
HelloAll.WelcometoFace
Input 2:
F a c e
Output 2:
Face
Algorithm to remove spaces from a string
● Input the string.
● Convert the string as character array.
● Traverse the character array.
● If the character encountered is not an empty space, print it.
● If the character encountered is an empty space, skip the character.
Algorithm to find the sum of all numbers present in the
string
● Input the string from the user.
● Initialize sum = 0.
● Find the numbers that are present in the string and add it with sum.
● Display sum.
C++ program to find the sum of all numbers present in the string */
#include <bits/stdc++.h>
using namespace std;
Function to find the sum of all numbers present in the string
int calculate_sum(string str)
string temp = “”; // intitialize temp
int sum = 0; // initialize sum
for (char ch: str) // traverse the characters one by one
{
if (isdigit(ch)) // if the character is a digit
temp += ch; // add that character to temp
else
{
sum += atoi(temp.c_str()); // add it with sum
temp = “”;
}
}
return sum + atoi(temp.c_str()); // return the sum
/*
//
{
}
● More than one occurrence of spaces between two words.
● There can be a single word like 'a' that needs to be capitalized.
● There may be two words like "me" where both letters must be capitalized.
Algorithm to capitalize first and last letter of each word in a
line
1. Create and initialize a hash table.
2. Insert the index of first letter( 0) & the index of last letter ( length-1).
Length is the length of the input line.
3. Iterate from i=0 to length-1
4. Find the index of spaces that are present in the line.
5. If index before spaces are not in the hash table
6. Insert them into the hash table
7. If index after spaces are not in the hash table
8. Insert them into the hash table
9. Capitalize the indexes present in the hash table
10. line [index]-=32;
11.//ASCII value of lower case letter -ASCII value of corresponding upper
case letter=32
12. Print the converted input line
C++ program to capitalize first and last letter of each word in a line
#include <bits/stdc++.h>
using namespace std;
void capital(char* arr, int i);
int main()
char sentence[100], c;
int i=0;
printf(“\nEnter the word : “) ;
scanf(“%c”,&c);
while(c!=’\n’)
sentence[i++]=c;
scanf(“%c”,&c);
capital(sentence,i);
return 0;
void capital(char* arr, int i)
//
{
{
}
} {
unordered_set str;
str.insert(0); // first char index
str.insert(i-1); // last char index
for(int j=1;j<i;j++)
if(arr[j]==’ ‘)
//Last letter of word is before space & first letter of word is after space
//check index already present in hash table or not if not insert index
if(str.find(j-1)==str.end())
str.insert(j-1);
if(str.find(j+1)==str.end())
str.insert(j+1);
//capitalize the first and last char
for(auto i=str.begin(); i!=str.end(); i++)
arr[*i]-=32;
//display
for(int j=0;j<i;j++)
printf(“%c”,arr[j]);
printf(“\n”);
{
{
}
}
}
● Input the string from the user.
● Traverse the string, character by character and store the count of each of the
characters in an array.
● Print the array that contains the frequency of all the characters.
C++ Program to Find the Frequency of Characters in a String */
#include <bits/stdc++.h>
using namespace std;
int main()
char str[100];
/*
{ int i;
Sample Input 1:
teeterson
Sample Output 1:
Sample Input 2:
charactercharacter
Sample Output 2:
All characters are repetitive
Algorithm to find the first non-repeating character in a
string
r
● Input the string from the user.
● Start traversing the string using two loops.
● Use the first loop to scan the characters of the string one by one.
● Use the second loop to find if the current character is occurring in the latter part if
the string or not.
● If it is not occurring, print that character.
● Else, continue traversing.
/* C++ program to find first non-repeating character */
#include<stdlib.h>
#include<iostream>
using namespace std;
#define NO_OF_CHARS 256
int *get_char_count(char *str)
int *count = (int *)calloc(sizeof(int), NO_OF_CHARS);
int i;
for (i = 0; *(str+i); i++)
count[*(str+i)]++;
return count;
int first_non_repeating_character(char *str)
int *count = get_char_count(str);
int index = -1, i;
for (i = 0; *(str+i); i++)
{
if (count[*(str+i)] == 1)
{
index = i;
break;
}
}
free(count);
return index;
{
}
{
}
● Input the two strings.
● Create an array for both the strings.
● Traverse both the strings and store the count of the alphabets of both the strings
in respective arrays.
● Check if both the arrays are equal.
● If both the arrays are equal, return true. Else, return false.
// C++ program to check if the two strings are anagrams or not
#include <bits/stdc++.h> using namespace std; int check_anagram(string s1, string s2); int main() { int n; string s1,s2; cout <<“\nEnter two strings : “; cin>>s1; cin>>s2; if(check_anagram(s1,s2)) printf(“\nYes\n”); else printf(“\nNo\n”); return 0;
} int check_anagram(string s1,string s2)
{ int a1[26]={0}, a2[26]={0};
//if string lengths are different then they are not anagrams if(s1.length()!=s2.length()) return 0;
// count the frequency of char in both strings
//for string1 – storing frequency for each letter in the string for(int i=0; s1[i]!=’\0′; i++)
{ a1[s1[i]-‘a’]++;
}
//storing frequency for each letter in the string for(int i=0; s2[i]!=’\0′; i++)
{ a2[s2[i]-‘a’]++;
}
//Anagram check – comparison step the frequencies of each char in both strings for(int i=0; i<26; i++)
{ if(a1[i] != a2[i]) return 0; } return 1;
}
ii) Algorithm to check if two strings are anagrams or not using sorting technique
● Input the strings.
● Sort both the strings.
● If both the strings are equal, return true. Else, return false.
// C++ program to check if the strings are anagrams
#include <bits/stdc++.h> using namespace std;
// function to check whether two strings are anagram of each other bool areAnagram(string str1, string str2)
{
// Get lengths of both strings int n1 = str1.length(); int n2 = str2.length();
// If length of both strings is not same, then they
// cannot be anagram if (n1 != n2) return false;
// Sort both the strings sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end());
// Compare sorted strings
for (int i = 0; i < n1; i++) if (str1[i] != str2[i]) return false;
return true;
} int main()
{ string str1; string str2; cout << “\nInput the strings : “; cin >> str1 >> str2; if (areAnagram(str1, str2)) cout << “The two strings are anagram of each other”; else cout << “The two strings are not anagram of each other”;
return 0;
}
16) Program to find all the patterns of 0(1+)0 in the given string is discussed here. Given a string containing 0's and 1's, find the total number of 0(1+)0 patterns in the string and output it.
0(1+)0 - There should be at least one '1' between the two 0's.
For example, consider the following string.
Input: 01101111010
Output: 3
Explanation:
01101111010 - count = 1
011011110 10 - count = 2
01101111 010- count = 3
Algorithm to find all the patterns of 0(1+)0 in the given string
● Input the given string.
● Scan the string, character by character.
● If the given pattern is encountered, increment count. ● Print count.
/* C++ program to find all the patterns of 0(1+)0 in the given string */
#include <bits/stdc++.h>
using namespace std;
/* Function to count the patterns */
int find_pattern(string str)
{ char last = str[0];
int i = 1, counter = 0;
while (i < str.size())
{
/* We found 1 and last character was ‘0’, state change*/
if (str[i] == ‘1’ && last == ‘0’)
{
while (str[i] == ‘1’)
i++;
/* After the stream of 1’s, we got a ‘0’, counter incremented*/
if (str[i] == ‘0’)
counter++;
}
/* Store the last character */
last = str[i];
i++;
} return counter;
} int main()
{
string str; cout << “nEnter the string : “;
cin >> str; cout << “Number of patterns found : ” << find_pattern(str) << endl;
return 0;
}
17) Program to replace a substring in a string is discussed here. The steps for replacing a substring with another string are given below.
Input: hi hello string to be replaced: hi string to be replaced with: hey
output: hey hello
Algorithm to Replace a substring in a string
● Input the full string (s1).
● Input the substring from the full string (s2).
● Input the string to be replaced with the substring (s3).
● Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).
// C++ code to replace a substring in a string
#include <iostream.h> #include <cstring> using namespace std;
int main() { string str, str2, str3; cout<<"Enter the main String: "; cin>>str; cout<<"Enter the string to be replaced: "; cin>>str2; int str2len = str2.length(); cout<<"Enter the replacing string: "; cin>>str3; str.replace(str.find(str2),str2.size(),str3); cout<<str; return 0;
}
18) Program to count the common sub sequence of two strings is discussed here. Given two strings, count all the common sub-sequences of the two strings and print it.
For example,
Input: string 1 = "abcd" string 2 = "abc"
Output:
Number of common sub-sequences = 7
Common sub-sequences: 'a', 'b', 'c', 'ab', 'bc', 'ac', 'abc'.
Input:
String 1 : bajdpmk
String 2 : dimnkc
Output:
Number of common sub-sequences = 7
Common sub-sequences: 'd', 'k', 'm', 'dk', 'km', 'dm', 'dmk'.
Algorithm to count the common sub sequence of two strings
● Input both the strings.
● Define arr[i][j] = arr[i][j-1] + arr[i-1][j] + 1, when s1[i-1] is equal to s2[j-1]
● When s1[i-1] == s1[j-1], all previous common sub-sequences are doubles as they get appended by one another character.
● Both arr[i][j-1] and arr[i-1][j] contain arr[i-1][j-1] and hence it gets added two times in recurrence which takes care of doubling the count of all previous common sub-sequences.
● Addition of 1 in recurrence is done for the latest character match, which is the common sub-sequence made up of s1[i-1] and s2[j-1]= arr[i-1][j] + arr[i][j-1] arr[i-1][j-1], when s1[i-1] is not equal to s2[j-1].
● Subtract arr[i-1][j-1] once because it is present in both arr[i][j 1] and arr[i 1][j] and is added twice.
/* C++ program to count the common sub sequence of two strings */
#include <bits/stdc++.h>
using namespace std;
// Function to find common sub sequence in both strings
int count_common_sub_sequence(string s1, string s2)
{
int n1, n2;
n1 = s1.length();
n2 = s2.length();
int arr[n1+1][n2+1];
for (int i = 0; i <= n1; i++)
{
for (int j = 0; j <= n2; j++)
{
arr[i][j] = 0;
}
}
// for each character of S1
for (int i = 1; i <= n1; i++)
{
// for each character in S2
for (int j = 1; j <= n2; j++)
{
// if character are same in both the string
if (s1[i – 1] == s2[j – 1])
{
arr[i][j] = 1 + arr[i][j – 1] + arr[i – 1][j];
} else
{
arr[i][j] = arr[i][j – 1] + arr[i – 1][j] – arr[i – 1][j – 1];
}
}
}
return arr[n1][n2];
} int main()
{ string s1; string s2; cout << “nEnter string 1 : “;
cin >> s1; cout << “nEnter string 2 : “;
cin >> s2; cout << “nCount of common sub sequence of two strings : ” << count_common_sub_sequence(s1, s2) << endl;
return 0;
}
19) A string can be reversed using the following approaches.
● Method 1: By swapping the characters of the string
● Method 2: By using recursion
● Method 3: By using standard library functions
Consider the below I/O samples before you program to reverse a string.
SAMPLE INPUT 1: faceprep
SAMPLE OUTPUT 1: perpecaf
SAMPLE INPUT 2: welcome
SAMPLE OUTPUT 2: emoclew
Method 1: Reverse a string by swapping the characters
The algorithm used in this method to reverse a given string is:
● Input the string from the user
● Find the length of the string. The actual length of the string is one less than the number of characters in the string. Let actual length be j.
● Repeat the below steps from i = 0 to the entire length of the string.
● rev[i] = str[j]
● Print the reversed string.
//program to reverse a string in C++
#include <iostream> using namespace std; int main() { char str[1000], rev[1000];
int i, j, count = 0; cin >> str;
//finding the length of the string by counting while (str[count] != '')
{ count++;
} j = count - 1;
//reversing the string by swapping
for (i = 0; i < count; i++)
{
rev[i] = str[j]; j--; } cout << rev; }
Method 2: Program to reverse a string using recursion
//program to reverse a string using recursion in C++
#include <iostream> #include <string.h> using namespace std;
#function to reverse a string
void reverse(char *x, int begin, int end)
{ char c; if (begin >= end) return;
c = *(x + begin);
*(x + begin) = *(x + end);
*(x + end) = c;
reverse(x, ++begin, --end);
}
int main() { char a[100]; cin >> a; reverse(a, 0, strlen(a) - 1); cout << a; return 0;
}
Method 3: Program to reverse a string using the standard library function
#include <bits/stdc++.h> using namespace std; int main() { string str; cin >> str; reverse(str.begin(), str.end()); cout << str << endl;
}
20) Program to check if two strings match where one string contains wildcard characters is discussed here.
DESCRIPTION:
Given a text and pattern string. The pattern consists of the following characters
+: It can be replaced with 0 or more occurrence of the previous character
*: Matches any sequence of characters (including the empty sequence) ?: It can be replaced with a single occurrence of any character.
The task is to determine if the string and pattern match after successfully replacing the special characters in the pattern with the above rules. Print true if the text and pattern match else print false
Test Cases:
The first string is the pattern and the second string represents the text
Sample Input 1:
String 1: Am?zo
String 2: Amazon
Sample Output 1:
FALSE
Sample Input 2:
String 1:Am?z*on
String 2:Amazkfdsaon
Sample Output 2:
TRUE
Algorithm to check if two strings match where one string contains wildcard characters
● Input two strings where string 1 contains wildcard characters.
● Check both the strings character by character.
● If a character of string 1 contains a '*' or '+', take the next character from string 1 and check for that character in string 2. If found, continue checking the next character, else return false.
● If the character of string 1 contains a '?', check if the immediate next character of string 1 and the next character of string 2 match. If they match, proceed checking with the next character. Else, return false.
● Continue the same process until all the characters have been traversed.
/* C++ program to check if the two strings are same where one strings contains wildcard characters */
#include <iostream>
using namespace std;
int main() { string pattern,checkS;
cin>>pattern; cin>>checkS; bool TRUE=true,FALSE=false;
bool dp[pattern.length()+1][checkS.length()+1];
dp[0][0]=TRUE; for(int i=1;i<=checkS.length();i++)
dp[0][i]=FALSE; for(int i=1;i<=pattern.length();i++)
if(pattern[i-1] == ‘*’)
dp[i][0]=dp[i-1][0]; else dp[i][0]=FALSE; for(int i=1;i<=pattern.length();i++)
{
for(int j=1;j<=checkS.length();j++)
{
if(pattern[i-1] == checkS[j-1])
dp[i][j]=dp[i-1][j-1];
else if(pattern[i-1] == ‘?’)
dp[i][j]=dp[i-1][j-1];
else if(pattern[i-1] == ‘*’) dp[i][j]=dp[i-1][j]||dp[i][j-1];
else if(pattern[i-1] == ‘+’)
{
if(pattern[i-2] == checkS[j-1])
{
dp[i][j]=dp[i-1][j] or dp[i][j-1];
}
else
{
dp[i][j] =FALSE;
}
}
else
{
dp[i][j] =FALSE;
}
}
}
// for(int i=1;i<=pattern.length();i++)
// {
// for(int j=1;j<=checkS.length();j++)
// {
// cout<<dp[i][j]<<” “;
// }
// cout<<endl;
// }
if(dp[pattern.length()][checkS.length()])
cout<<“TRUE”;
else cout<<“FALSE”;
}
Test Case 1
I/P
F*CE
FACE
O/P
TRUE
TestCase 2
I/P
F*SA+C*YFORCAR+E*E+M*T
FOCUSACADEMYFORCARRERENHANCEMENT
O/P
TRUE
Test Case 3
I/P
No+No+
NoooooooooooNooooaoooooo
O/P
FALSE
TestCase 4
I/p
*
Face
O/P
TRUE
TestCase 5
I/p
Am?azon
Amazon
O/p
FALSE
0 Comments