Welcome to Day 4 of my 100 Days of DSA journey! Today, I worked with strings, which are essential for text manipulation in programming. Strings are widely used in various applications like text processing, searching, and pattern matching. To strengthen my skills, I tackled five problems, from reversing a string to identifying the longest word in a given string. These exercises helped deepen my understanding of string operations and their practical applications. Let’s dive in!
I have also maintained a GitHub repository for the same, so feel free to check it out: github.com/AayJayTee/100-Days-DSA.
Q1. Write a program to reverse a string.
#include <iostream>
using namespace std;
// Function to reverse a given string
void reverseString(string str) {
// Create a new string 'rev' of the same length as the input string
string rev(str.size(), ' ');
int j = 0; // Variable to track the index of 'rev' string
// Loop through the input string from the end to the beginning
for (int i = str.size() - 1; i >= 0; i--) {
rev[j] = str[i]; // Place the characters from 'str' into 'rev'
j++; // Move to the next position in 'rev'
}
// Print the reversed string
cout << "Reversed string is: " << rev;
}
int main() {
string str;
// Take input from the user
cout << "Enter string: ";
cin >> str;
// Call the function to reverse the string
reverseString(str);
return 0;
}
This program reverses a given string by iterating through the string from the end to the beginning, placing each character into a new string. It utilizes a simple approach of creating an empty string rev
of the same length as the input string str
. The program loops through the input string in reverse order and fills rev
with characters from str
. Once the reversal is complete, it prints the reversed string.
Q2. Check if a given string is a palindrome.
#include <iostream>
using namespace std;
// Function to check if a string is a palindrome
bool isPalindrome(string str) {
int i = 0; // Start pointer at the beginning of the string
int j = str.size() - 1; // End pointer at the last character of the string
bool flag = true; // Flag to track if the string is a palindrome
// Check characters from both ends of the string towards the center
while (i != j && i < str.size() && j >= 0) {
if (str[i] != str[j]) { // If characters don't match, set flag to false
flag = false;
}
i++, j--; // Move both pointers towards the center
}
return flag; // Return true if the string is a palindrome, otherwise false
}
int main() {
string str;
// Take input from the user
cout << "Enter string: ";
cin >> str;
// Call the function to check if the string is a palindrome
if (isPalindrome(str)) {
cout << "String is a palindrome"; // Print message if it's a palindrome
} else {
cout << "String is not a palindrome"; // Print message if it's not
}
return 0;
}
This program checks if a given string is a palindrome. A palindrome is a word, phrase, or sequence of characters that reads the same backward as forward. The algorithm works by using two pointers: one starting at the beginning of the string (i
) and the other at the end (j
). It compares the characters at these positions. If they are not equal, the string is not a palindrome. The pointers move towards the center, and the process continues until the entire string is checked. If all corresponding characters match, the string is a palindrome.
Q3. Write a function to count vowels and consonants in a string.
#include <iostream>
using namespace std;
// Function to count vowels and consonants in a string
void count_vowel_consonant(string str) {
int nofv = 0; // Variable to count the number of vowels
int nofc = 0; // Variable to count the number of consonants
// Loop through each character in the string
for (int i = 0; i < str.size(); i++) {
// Check if the current character is a vowel (case insensitive)
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') {
nofv += 1; // Increment vowel count if it's a vowel
} else if (isalpha(str[i])) { // Check if the character is a letter
nofc += 1; // Increment consonant count if it's a consonant
}
}
// Output the counts of vowels and consonants
cout << "No. of vowels in the string are: " << nofv << endl;
cout << "No. of consonants in the string are: " << nofc << endl;
}
int main() {
string str;
// Take input from the user
cout << "Enter string: ";
cin >> str;
// Call the function to count vowels and consonants
count_vowel_consonant(str);
return 0;
}
This program counts the number of vowels and consonants in a given string. It checks each character in the string, and if it is a vowel (either lowercase or uppercase), it increments the vowel count. If the character is a letter but not a vowel, it is considered a consonant, and the consonant count is incremented. Non-alphabetic characters are ignored.
Q4. Implement a program to remove duplicate characters from a string.
#include <iostream>
using namespace std;
// Function to remove duplicate characters from a string
void remove_duplicate(string str) {
string newstr = ""; // String to store result without duplicates
// Iterate through the original string
for (int i = 0; i < str.size(); i++) {
bool flag = false;
// Check if the character already exists in the new string
for (int j = 0; j < newstr.size(); j++) {
if (str[i] == newstr[j]) {
flag = true; // Mark as duplicate if character exists
break;
}
}
// If the character is not a duplicate, append it to the result string
if (!flag) {
newstr += str[i];
}
}
// Output the string with duplicates removed
cout << "String after removal of duplicates is: " << newstr;
}
int main() {
string str;
cout << "Enter string: ";
cin >> str;
// Call function to remove duplicates
remove_duplicate(str);
return 0;
}
This program removes duplicate characters from a given string by iterating over it and adding each character to a new string only if it hasn’t appeared before. It uses a flag to check whether a character is already included in the result string. Non-duplicate characters are appended to the new string, and the final result is printed.
Q5. Solve the "longest word in a string" problem.
//Q. Solve the "longest word in a string" problem.
#include <iostream>
using namespace std;
#include <sstream>
void longestword(string str,int n){
stringstream ss(str); // Create a stringstream from the input string
string word;
string longestWord = ""; // Variable to keep track of the longest word
// Process each word from the stringstream
while (ss >> word) {
if (word.size() > longestWord.size()) {
longestWord = word; // Update the longest word if the current word is longer
}
}
cout<<"The longest word is: "<<longestWord;
}
int main()
{
string str;
cout<<"Enter string: ";
getline(cin,str);
longestword(str,str.size());
return 0;
}
This program solves the problem of finding the longest word in a given string. It uses the stringstream
to split the string into words and compares the length of each word to determine the longest one. The longest word is then printed to the console.
Today’s practice allowed me to enhance my understanding of string manipulation and its various operations. Whether it was reversing a string, checking for palindromes, or counting vowels and consonants, each problem presented a unique challenge. These exercises also provided valuable insights into how strings are handled in different contexts, especially when removing duplicates or finding the longest word. As I move forward, I’m excited to continue exploring more advanced string algorithms and their real-world applications. Onward to Day 5!