How to Convert a String to Camel Case in C++ using a Simple Loop

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:-
  1. Traverse the input character by character.
  2. If a space is encountered, mark a flag.
  3. The next alphabet after a space is capitalized.
  4. 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"

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top