Practical work
1) Remove all characters except alphabets
This program takes a string (object) input from the user and removes all characters except alphabets.
#include <iostream>
using namespace std;
int main() {
string line;
cout << "Enter a string: ";
getline(cin, line);
for(int i = 0; i < line.size(); ++i)
{
if (!((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z')))
{
line[i] = '\0';
}
}
cout << "Output String: " << line;
return 0;
}
Output
Enter a string: p2'r"o@gram84iz./
Output String: programiz
2) Remove all characters except alphabets
This program below takes a string (C-style string) input from the user and removes all characters except alphabets.
#include <iostream>
using namespace std;
int main() {
char line[100], alphabetString[100];
int j = 0;
cout << "Enter a string: ";
cin.getline(line, 100);
for(int i = 0; line[i] != '\0'; ++i)
{
if ((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z'))
{
alphabetString[j++] = line[i];
}
}
alphabetString[j] = '\0';
cout << "Output String: " << alphabetString;
return 0;
}
Output
Enter a string: P2'r"o@gram84iz./
Output String: Programiz
3) You will learn to compute the length (size) of a string (both string objects and C-style strings).
Example: Length of String Object
#include <iostream>
using namespace std;
int main()
{
string str = "C++ Programming";
// you can also use str.length()
cout << "String Length = " << str.size();
return 0;
}
Output
String Length = 15
Example: Length of C-style string
To get the length of a C-string string, strlen() function is used.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "C++ Programming is awesome";
// you can also use str.length()
cout << "String Length = " << strlen(str);
return 0;
}
Output
String Length = 26
In this example, frequency of occurrence of a character is checked for both (String object and C-style string).
Example 1: Find Frequency of Characters of a String Object
#include <iostream>
using namespace std;
int main()
{
string str = "C++ Programming is awesome";
char checkCharacter = 'a';
int count = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == checkCharacter)
{
++ count;
}
}
cout << "Number of " << checkCharacter << " = " << count;
return 0;
}
Output
Number of a = 2
4) Loop is iterated until the null character '\0' is encountered. Null character indicates the end of the string.
In each iteration, the occurrence of the character is checked.
Example 2: Find Frequency of Characters in a C-style String
#include <iostream>
using namespace std;
int main()
{
char c[] = "C++ programming is not easy.", check = 'm';
int count = 0;
for(int i = 0; c[i] != '\0'; ++i)
{
if(check == c[i])
++count;
}
cout << "Frequency of " << check << " = " << count;
return 0;
}
Output
Number of m = 2
Материалы на данной страницы взяты из открытых источников либо размещены пользователем в соответствии с договором-офертой сайта. Вы можете сообщить о нарушении.