code.cpp 859 B

12345678910111213141516171819202122232425262728293031
  1. /* Create two functions toCamelCase() and toSnakeCase() that each take
  2. * a single string and convert it into either camelCase or snake_case.
  3. * If you're not sure what these terms mean, check the Resources tab above.
  4. */
  5. // rule 1, check for capitals
  6. // rule 2, check for underscore
  7. std::string toSnakeCase(std::string str) {
  8. for(int i = 0;i<str.size();i++){
  9. // insert an underscore before the uppercase
  10. if(isupper(str[i])){
  11. // set uppercase to lowercase
  12. str[i]=tolower(str[i]);
  13. str.insert(str.begin()+i,'_');
  14. }
  15. }
  16. return str;
  17. }
  18. std::string toCamelCase(std::string str) {
  19. int p;
  20. // find underscore in string
  21. while(std::string::npos != (p = str.find('_'))){
  22. // capitalize character after underscore
  23. if(str.size() != (p+1)){
  24. str[p+1]=toupper(str[p+1]);
  25. }
  26. // remove underscore
  27. str.erase(p,1);
  28. }
  29. return str;
  30. }