Skip to content

strings

codingdud edited this page Sep 7, 2024 · 1 revision

Table of Contents

  1. String Manipulation
  2. cp-questions

String Manipulation

Convert Integer to String and Append

Question: How do you convert an integer to a string, append to it, and then convert the string back to an integer?

Code Explanation:

#include<bits/stdc++.h>
using namespace std;

int main() {
    int nums;
    cin >> nums;
    string s = to_string(nums);      // Convert integer to string
    cout << s + '1' << "\n";         // Append '1' to the string and print
    int n1 = stoi(s);                // Convert string back to integer
    cout << n1 + 1;                  // Add 1 to the integer and print
}

Explanation:

  • Conversion: The to_string() function converts an integer nums into a string s.
  • Appending: '1' is appended to s, and the result is printed.
  • String to Integer: The stoi() function converts the string back to an integer, and 1 is added to it.
  • Output: This demonstrates the basic conversion between strings and integers in C++.

Remove Outer Parentheses from a String

Question: How do you remove the outermost parentheses from each primitive string in a valid parentheses string?

Code Explanation:

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    string removeOuterParentheses(string s) {
        string res = "";
        int balance = 0;
        for (char c : s) {
            if (c == '(') {
                if (balance > 0) {
                    res.push_back(c);    // Only add '(' if it's not an outer one
                }
                balance += 1;
            } else if (c == ')') {
                balance -= 1;
                if (balance > 0) {
                    res.push_back(c);    // Only add ')' if it's not an outer one
                }
            }
        }
        return res;
    }
};

Explanation:

  • Logic: This function removes the outermost parentheses in each valid primitive string.
  • Balance: The balance variable keeps track of the depth of nested parentheses.
    • If the balance is positive, it means the parentheses are not outermost, so they are added to the result.
  • Efficiency: This approach ensures that only the inner parentheses are kept, while the outermost ones are discarded.

Basic String Operations

Question: How do you perform basic string operations like size, front, back, pop, push, and transform?

Code Explanation:

#include<bits/stdc++.h>
using namespace std;

int main() {
    string s = "hello world";
    cout << s << endl;                 // Print the string
    cout << s.size() << endl;          // Get size of the string
    cout << s.length() << endl;        // Get length of the string
    cout << s.front() << endl;         // Get the first character
    cout << s.back() << endl;          // Get the last character
    s.pop_back();                      // Remove the last character
    s.push_back('w');                  // Add 'w' to the end
    cout << s.back() << endl;          // Print the new last character
    s.insert(0, "AKanoob ");           // Insert a string at the beginning
    cout << s << endl;
    transform(s.begin(), s.end(), s.begin(), ::toupper);  // Convert to uppercase
    cout << s << endl;
    transform(s.begin(), s.end(), s.begin() + 3, ::tolower);  // Convert after 3rd char to lowercase
    cout << s << endl;
}

Explanation:

  • String Properties: size(), length(), front(), and back() provide basic information about the string.
  • Modifications: pop_back(), push_back(), and insert() modify the string.
  • Transformations: The transform() function is used to convert the string to uppercase and lowercase.

Iterate and Transform String Characters

Question: How do you iterate over a string and manipulate character ASCII values?

Code Explanation:

#include<bits/stdc++.h>
using namespace std;

int main() {
    string s = "abcd";
    for (int i : s) {
        cout << i << " ";              // Print ASCII values of characters
    }
    int num = 69;
    cout << (char)num << " ";          // Convert ASCII value to character
    cout << s[1] - s[0];               // Print difference between ASCII values of s[1] and s[0]
}

Explanation:

  • Iteration: The loop iterates through each character in the string and prints its ASCII value.
  • Type Casting: (char)num converts an integer to its corresponding ASCII character.
  • Character Difference: s[1] - s[0] calculates the difference between ASCII values of two characters.

Extract Substring and Find Substring

Question: How do you extract a substring from a string and find the position of a substring?

Code Explanation:

#include<bits/stdc++.h>
using namespace std;

int main() {
    string sne = "Hy, I am a react developer!";
    string s = sne.substr(4, 4);       // Extract 4 characters starting from index 4
    cout << s;
    
    size_t pos = sne.find("jsjfsdfg"); // Find a substring that doesn't exist
    cout << pos << endl;               // Print position (will output -1 if not found)
}

Explanation:

  • Extracting Substring: substr(start, length) extracts a substring starting at a specific index for a given length.
  • Finding Substring: find() searches for a substring in a string and returns its position. If not found, it returns string::npos, which is typically -1.
Clone this wiki locally