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){
}
#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
Comments
Leave a comment