Day 4: Strings Basics

Day 4: Strings Basics

Welcome to Day 4 of my 100 Days of DSA challenge! Today, I focused on solving five intriguing string-based problems. Strings are at the heart of many programming challenges, and mastering them is key to tackling a variety of real-world scenarios and interview questions.

In this session, I explored different aspects of string manipulation, from basic operations to more complex transformations. Below, you’ll find the problems I worked on, along with their C++ implementations. Dive in to see how I approached each challenge.

Check out my GitHub repository for all the solutions and progress updates at: 100 Days of DSA

Let’s keep pushing forward! 🚀✨


1. Reverse a String

This program reverses a string, including spaces, entered by the user. It uses getline to read multi-word input and a loop to reverse the string by copying characters from the end of the input string to the beginning of a new string.

Code:

#include <iostream>
#include <string>
using namespace std;

//Function to reverse a string
void reverse_str(string str) {
    int n = str.length();
    string rev_str = str;     // Initialize rev_str with the same size as str

    // Reverse the string
    for (int j = n - 1, i = 0; j >= 0; j--, i++) {
        rev_str[i] = str[j];
    }

    cout << "The reversed string is: " << rev_str << endl;
}

int main() {
    string str;
    cout << "Enter a string: ";
    getline(cin, str);       // Use getline to read the full line including spaces
    reverse_str(str);
    return 0;
}

Output:


2. Check if String is Palindrome

This code checks whether a given string is a palindrome, ignoring case differences. It uses a loop to compare characters from the start and end of the string while moving towards the center. The tolower() function ensures case-insensitive comparisons by converting characters to lowercase.

Code:

#include <iostream>
#include <cctype>
using namespace std;

// Function to check if a given string is a palindrome
void palindrome_check(string str) {
    int n = str.length();
    bool is_palindrome = true;

    // Loop to compare characters from the start and end of the string
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        // Convert both characters to lowercase for case-insensitive comparison
        if (tolower(str[i]) != tolower(str[j])) {
            is_palindrome = false;
            break; // No need to continue if a mismatch is found
        }
    }

    // Check the result and print the appropriate message
    if (is_palindrome) {
        cout << "String is Palindrome." << endl;
    }
    else {
        cout << "String is not Palindrome." << endl;
    }
}

int main() {
    string str;
    cout << "Enter a string: ";
    cin >> str;
    palindrome_check(str);
    return 0;
}

Output:


3. Count Vowels and Consonants in a String

This code counts the number of vowels and consonants in a given string. First, it converts the string to lowercase to make the comparison case-insensitive. Then, it iterates through the string, checking each character. If the character is an alphabetic letter, it checks whether it's a vowel or consonant and updates the respective count. Finally, it prints the total count of vowels and consonants in the string.

Code:

#include <iostream>
#include <cctype>
using namespace std;

// Function to count vowels and consonants in a string
void vowels_consonants(string str) {
    int vowel_count = 0;
    int consonant_count = 0;

    // Convert the string to lowercase manually character by character
    for (int i = 0; i < str.length(); i++) {
        str[i] = tolower(str[i]);
    }

    // Loop through the string and count vowels and consonants
    for (int i = 0; i < str.length(); i++) {
        if (isalpha(str[i])) {      // Only check alphabetic characters
            if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') {
                vowel_count++;
            }
            else {
                consonant_count++;
            }
        }
    }

    cout << "Number of vowels: " << vowel_count << endl;
    cout << "Number of consonants: " << consonant_count << endl;
}

int main() {
    string str;
    cout << "Enter a string: ";
    cin >> str;
    vowels_consonants(str);
    return 0;
}

Output:


4. Remove Duplicate Characters from a String

This code removes duplicate characters from a string. It iterates through the string and checks if each character has already appeared earlier using the is_present function. If a character is not found in the part of the string that has already been processed, it is moved to the "new" part of the string. The string is then truncated to remove any remaining characters after the unique ones, and the result is displayed.

Code:

#include <iostream>
using namespace std;

// Function to check if a particular character is present in a string
bool is_present(char ch, string str) {
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == ch) {
            return true;
        }
    }
    return false;
}

//Function to remove duplicate characters from a string
void remove_duplicates(string str) {
    int n = str.size();
    int newLength = 0;

    // Iterate through the string
    for (int i = 0; i < n; i++) {
        // If the character is not already in the result, move it to the 'new' part of the string
        if (!is_present(str[i], str.substr(0, newLength))) {
            str[newLength] = str[i];
            newLength++;
        }
    }

    // Cut off any extra characters after the new length
    str = str.substr(0, newLength);

    cout << "String after removing duplicate characters is: " << str;
}

int main() {
    string str;
    cout << "Enter the string: ";
    cin >> str;
    remove_duplicates(str);
}

Output:


5. Longest Word in String

This code finds the longest word in a given string. It uses a stringstream to split the string into words. For each word, it checks if its length is greater than the previously found longest word. The program keeps track of the longest word and its length and outputs them at the end. The string is input using getline() to ensure it captures the entire line, including spaces.

Code:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

// Function to find the longest word in a string
void find_longest_word(string str) {
    stringstream stream(str);       // Create a stringstream to split the string into words
    string word;
    string longest = ""; 
    int max_len = 0; 

    // Loop through all words in the string
    while (stream >> word) {
        // Check if the current word is longer than the previously found longest word
        if (word.length() > max_len) {
            max_len = word.length();
            longest = word;
        }
    }

    cout << "Longest word: " << longest << endl;
    cout << "Length of Longest Word: " << max_len << endl;
}

int main() {
    string str;
    cout << "Enter a string: ";
    getline(cin, str);        // Read the entire line of input
    find_longest_word(str);
    return 0;
}

Output:


That’s a wrap for Day 4! Today, I dove into solving string manipulation problems. From reversing strings to finding the longest word, it was a day full of practical challenges that are crucial for problem-solving in coding interviews.

String operations are essential for tackling a wide range of real-world programming tasks, and I’ve definitely sharpened my skills today. It was exciting to apply different techniques and optimize solutions.

Can’t wait to dive into more challenges on Day 5! 🚀