Variable Naming Standards
National Olympiad — National round (2012 season)
Submission name: standarts.cpp
Problem summary
Convert a valid variable name between lowercase words joined by underscores and words joined directly with every word’s initial letter uppercase (including the first word).
Input
n and then a valid name in one of the two standards.
Output
The equivalent name in the other standard.
Constraints
1 ≤ n ≤ 60; only Latin letters and underscores occur.
Worked example
An independently prepared example for this explanation.
Input
11 my_variable
Output
MyVariable
Solution analysis
- The first character identifies the standard: an uppercase initial means the capitalized-word standard; otherwise the name uses lowercase words.
- For capitalized words, insert an underscore before each uppercase letter except the first, then lowercase it. In the other direction, remove underscores and uppercase the first letter and each letter after an underscore.
- my_variable becomes MyVariable. ATest becomes a_test, because both A and T start words.
Why it works
In each direction, exactly the word boundaries are converted to the other standard’s boundary marker, while all word letters retain their lowercase form except the required initials. Therefore the same word sequence is represented correctly.
Watch out. The first word is capitalized too. Single-word names such as x must become X.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
string name;
cin >> n >> name;
if (name[0] >= 'A' && name[0] <= 'Z') {
for (int i = 0; i < n; i++) {
char letter = name[i];
if (letter >= 'A' && letter <= 'Z') {
// Each uppercase letter starts a word; omit the first separator.
if (i > 0) {
cout << '_';
}
letter = static_cast<char>(letter - 'A' + 'a');
}
cout << letter;
}
} else {
bool initial = true;
for (char letter : name) {
if (letter == '_') {
initial = true;
} else {
if (initial) {
letter = static_cast<char>(letter - 'a' + 'A');
}
cout << letter;
initial = false;
}
}
}
cout << '\n';
}