Given a list of strings words, concatenate the strings in camel case format.
Example 1
Inputwords = [“java”, “beans”]
Output“javaBeans”
Example 2
Inputwords = [“Go”, “nasa”]
Output“goNasa”
How to Convert a String into Camel Case in C++?
C++ doesn’t offer a function to convert a string to either uppercase or lowercase. However, we can utilize the std::toupper and std::tolower to convert a char to its corresponding form. We can wrap it in a lambda function:
1 2 3 4 5 6 | function<string(string)> stringToLower = [](string data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); return data; }; |
function<string(string)> stringToLower = [](string data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); return data; };
Then, the rest is simpler, make the first word lowercase, and then the rest words first character uppercase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | string solve(vector<string>& words) { if (words.empty()) return ""; function<string(string)> stringToLower = [](string data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); return data; }; string ans = stringToLower(words[0]); for (int i = 1; i < words.size(); ++ i) { ans += (char)std::toupper(words[i][0]); ans += stringToLower(words[i].substr(1)); } return ans; } |
string solve(vector<string>& words) { if (words.empty()) return ""; function<string(string)> stringToLower = [](string data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); return data; }; string ans = stringToLower(words[0]); for (int i = 1; i < words.size(); ++ i) { ans += (char)std::toupper(words[i][0]); ans += stringToLower(words[i].substr(1)); } return ans; }
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Compute the Nth Row of a Pascal's Triangle using Dynamic Programming Algorithm
Next Post: C++ Algorithm to Check if a String is Repeated