Answer to Question #220199 in C++ for sukki

Question #220199

You are given a string str, remove all special characters from it and convert all uppercase letters to lowercase, and return the new string.

Special characters are characters that are not letters and digits.

Eg1:

Input: str = "Hello, World 2!"

Output: "helloworld2"

Hint: 1. C++ has many useful functions for this question: isupper, islower, isalpha, isdigit.

string removeSpecialChars(string str){
        
}
1
Expert's answer
2021-07-24T07:02:42-0400
#include <iostream>

using namespace std;

string removeSpecialChars(string s)
{
    string ans = "";
    for (int i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) ans = ans + s[i];
        if ((s[i]>='A' && s[i]<='Z') || (s[i]>='a' && s[i]<='z'))
        {
            if (isupper(s[i])) ans = ans + (char) tolower(s[i]);
            else ans = ans + s[i];
        }
    }
    return ans;

}

int main()
{
    cout << removeSpecialChars("Hello, World 2!") << '\n';
    return 0;
}

Output:
helloworld2

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS