In this blog post, we’ll explore how to convert a string to camel case using a simple and beginner-friendly C++ program. Camel case is a common string formatting style used in programming, especially in variable and function names.
Convert a string to camel case using C++
What is Camel Case?
Camel case is a naming convention where:
- The first word is in lowercase.
- Each subsequent word starts with an uppercase letter.
- There are no spaces or underscores.
Approach:-
- Traverse the input character by character.
- If a space is encountered, mark a flag.
- The next alphabet after a space is capitalized.
- All other characters are made lowercase and added to the result.
C++ Code to Convert String to Camel Case:-
#include <bits/stdc++.h>
using namespace std;
string camelcase(string convert){
bool space=false;
string ans="";
for(int i=0;i<convert.length();i++){
if(convert[i]==' '){
space=true;
}
else{
if(space==true && isalpha(convert[i])){
ans+=toupper(convert[i]);
space=false;
}
else{
ans+=tolower(convert[i]);
}
}
}
return ans;
}
int main() {
string input="hello world from codespeedy";
cout<<camelcase(input)<<endl;
return 0;
}
Example:
Input → "hello world from codespeedy" Output → "helloWorldFromCodespeedy"