Here's the problem for Java vs C++ (JAVAC):
Java and C++ use different naming conventions:
- In Java a multiword identifier is constructed in the following manner:
- The first word is written starting from the small letter, and the following ones are written starting from the capital letter, no separators are used. All other letters are small.
Examples of a Java identifier are: javaIdentifier, longAndMnemonicIdentifier, name, nEERC.
- The first word is written starting from the small letter, and the following ones are written starting from the capital letter, no separators are used. All other letters are small.
- In C++ a multiword identifier is constructed in the following manner:
- Use only small letters in their identifiers. To separate words they use underscore character ‘_’.
Examples of C++ identifiers are: c_identifier, long_and_mnemonic_identifier, name
- Use only small letters in their identifiers. To separate words they use underscore character ‘_’.
Note: When identifiers consist a single word then Java and C++ naming conventions are identical:
You are writing a translator that is intended to translate C++ programs to Java and vice versa. Of course, identifiers in the translated program must be formatted due to its language naming conventions — otherwise people will never like your translator.
The first thing you would like to write is an identifier translation routine. Given an identifier, it would detect whether it is Java identifier or C++ identifier and translate it to another dialect. If it is neither, then your routine should report an error. Translation must preserve the order of words and must only change the case of letters and/or add/remove underscores.
How can I improve this code? How can I make it faster? Are there better solutions?
#include<iostream>
#include<string>
#include<cctype>
std::string convert(const std::string& s) {
std::string result{};
bool java = false;
bool cpp = false;
if (isupper(s[0]) || s[0] == '_' || s[s.size()-1] == '_') {
return "Error!";
}
for (std::size_t i = 0; i < s.size(); ++i) {
if (isupper(s[i])) {
cpp = true;
result += "_";
result += tolower(s[i]);
} else if (s[i] == '_') {
java = true;
if (isupper(s[i+1]) || s[i+1] == '_') {
return "Error!";
} else {
result += toupper(s[++i]);
}
} else if (isalpha(s[i])) {
result += s[i];
} else {
return "Error!";
}
}
if ((java != cpp) || (!java && !cpp)) {
return result;
} else {
return "Error!";
}
}
int main() {
do {
std::string str;
std::cin >> str;
std::cout << convert(str) << '\n';
} while (std::cin);
}