2. Solution #
Take the first example:
Hello World! How are you today?
It'll be easier to consider this problem as 2 smaller sub-problem: Converting a string to camel case, and removing all special characters from a string. We will go into the details of the solution with both C and C++, as well as things to keep in mind for each method.
1. Solution in C++
We first create a function 'toCamelCase(string str)' which takes a string as an input and converts it to camel case.
void to_camel_case(std::string &s) {
if (s.empty()) return;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ' || s[i] == '_') {
int j = i + 1;
if (j < s.length()) {
s[j] = toupper(s[j]);
}
}
}
}
Then, we design a function called 'removeSpecialChars(string str)' to return the input string after removing all special characters.
void remove_special_characters(std::string &s) {
if (s.empty()) return;
for (int i = 0; i < s.length(); i++) {
if (!isalnum(s[i])) {
s.erase(i, 1);
i--;
}
}
}
2. Solution in C
There seemes no obvious different when comparing to the solution in C++. First we convert string to camel case, then remove special characters.
void to_camel_case(char *s) {
if (s == NULL) return;
int len = strlen(s);
if (len == 0) return;
for (int i = 0; i < len; i++) {
if (s[i] == ' ' || s[i] == '_') {
int j = i + 1;
if (j < len) {
s[j] = toupper(s[j]);
}
}
}
}
void remove_special_characters(char *s) {
if (s == NULL) return;
int len = strlen(s);
if (len == 0) return;
for (int i = 0; i < len; i++) {
if (!isalnum(s[i])) {
for (int j = i; j < len; j++) {
s[j] = s[j + 1];
}
len--;
i--;
}
}
}
But we need to pay attention to the type of string in C.
In C++, we use the std::string class to handle strings, which provides a lot of helpful methods for manipulating strings, such as erase and empty. In C, we have to use arrays of characters, and manually manage memory allocation and deallocation.
The C++ implementation provides a more convenient and easier-to-use interface for string manipulation, while the C implementation provides a lower-level interface that gives you more control over memory and performance.
Finally, after execute 2 functions, we will be able to receive the desired result
Output
HelloWorldHowAreYouToday