Open In App

Convert first character uppercase in a sentence

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s, the task is to convert the first letter of each word in the string to uppercase

Note: Letters other than the first one must be converted to lowercase.

Examples: 

Input: s = “gEEKs”
Output: “Geeks”
Explanation: Given string s contains only single word “gEEKs”. The first letter is converted to the uppercase and the rest to the lowercase.

Input: s = “i love programming”
Output: “I Love Programming”
Explanation: Given string s contains three words “i”, “love” and “programming”. The first letter of each word is converted to uppercase and the other to lowercase.

Using Inbuilt method – O(n) Time and O(n) Space

Various programming languages provide different inbuilt methods and functions to convert a character to lowercase or uppercase accordingly.

C++
// C++ Program to convert first character
// of word in a string to uppercase
#include <bits/stdc++.h>
using namespace std;

// Function to convert first character
// of word in a string to uppercase
string convert(string s) {

    // Create a char array of given String
    stringstream str(s);
    string word;
    string result = "";

    // Declare a character of space
    // To identify that the next character is the starting
    // of a new word
    while (str >> word) {
        word[0] = toupper(word[0]);
        result.append(word);
        result.append(" ");
    }

    // remove the extra space at end of string
    result.pop_back();
    return result;
}

int main() {

    string s = "gEEks fOr GeeKs";
  
    // Convert that string into lowercase
    transform(s.begin(), s.end(), s.begin(), ::tolower);
    cout << convert(s);
    return 0;
}
C
// C Program to convert first character
// of word in a string to uppercase
#include <ctype.h>
#include <stdio.h>
#include <string.h>

void convert(char *s) {
    int len = strlen(s);
    char result[len + 1];

    for (int i = 0; i < len; i++) {

        // If first character of a word is found
        if ((s[i] != ' ') && (i == 0 || s[i - 1] == ' ')) {

            // Convert into Upper-case
            result[i] = toupper(s[i]);
        }
        else {
            result[i] = s[i];
        }
    }
    result[len] = '\0';
    printf("%s\n", result);
}

int main() {
    char s[] = "gEEks fOr GeeKs";

    // Convert that string into lowercase
    for (int i = 0; s[i] != '\0'; i++) {
        s[i] = tolower(s[i]);
    }
    convert(s);
    return 0;
}
Java
// Java Program to convert first character
// of word in a string to uppercase
class GfG {

    // Function to convert first character
    // of word in a string to uppercase
    static String convert(String s) {
        StringBuffer str = new StringBuffer();

        // Declare a character of space
        // To identify that the next character is the
        // starting of a new word
        char ch = ' ';
        for (int i = 0; i < s.length(); i++) {

            // If previous character is space and current
            // character is not space then it shows that
            // current letter is the starting of the word
            if (ch == ' ' && s.charAt(i) != ' ')
                str.append(
                    Character.toUpperCase(s.charAt(i)));
            else
                str.append(s.charAt(i));
            ch = s.charAt(i);
        }

        // Return the string with trimming
        return str.toString().trim();
    }

    public static void main(String args[]) {

        String s = "gEEks fOr GeeKs";

        // Convert that string into lowercase
        s = s.toLowerCase();
        System.out.println(convert(s));
    }
}
Python
# Python Program to convert first character
# of word in a string to uppercase
import string
import io

# Function to convert first character
# of word in a string to uppercase
def convert(s):

    # Create a stream from the string
    s = io.StringIO(s)
    result = ""

    # Declare a character of space
    # To identify that the next character is the starting
    # of a new word
    for word in s.read().split():

        # Convert that string into lowercase
        word = word.lower()

        # capitalize() convert first character
        # of word to uppercase
        word = word.capitalize()

        # append the word in result
        result = " ".join([result,word])

    # Return the string with trimming
    return result.strip()

if __name__ == "__main__":
    s1 = "gEEks fOr GeeKs"
    print(convert(s1))
C#
// C# Program to convert first character
// of word in a string to uppercase
using System;

class GfG {

    // Function to convert first character
    // of word in a string to uppercase
    static string convert(string s) {

        // Declare a character of space
        // To identify that the next character is the
        // starting of a new word
        char ch = ' ';
        string result = "";

        for (int i = 0; i < s.Length; i++) {

            // If previous character is space and current
            // character is not space then it shows that
            // current letter is the starting of the word
            if (ch == ' ' && s[i] != ' ') {
                result = string.Concat(result,char.ToUpper(s[i]));
            }
            else
                result = string.Concat(result,s[i]);
            ch = s[i];
        }

        return result.Trim();
    }

    static void Main(string[] args) {

        string s = "gEEks fOr GeeKs";

        // Convert that string into lowercase
        s = s.ToLower();
        Console.WriteLine(convert(s));
    }
}
JavaScript
// Javascript Program to convert first character
// of word in a string to uppercase
function convert(s) {

  // Declare a character of space
  // To identify that the next character is the
  // starting of a new word
  let result = "";
  let ch = " ";

  for (let i = 0; i < s.length; i++) {

    // If previous character is space and current
    // character is not space then it shows that
    // current letter is the starting of the word
    if (ch === " " && s.charAt(i) !== " ") {
      result = result.concat(s.charAt(i).toUpperCase());
    } 
    else {
      result = result.concat(s.charAt(i));
    }
    ch = s.charAt(i);
  }
  
  // Return the string with trimming
  return result.trim();
}

let s = "gEEks fOr GeeKs";

// Convert that string into lowercase
s = s.toLowerCase();
console.log(convert(s));

Output
Geeks For Geeks

Iterative Method – O(n) Time and O(1) Space

The first letter of the string and the letter after space ‘ ‘ character marks the beginning of the new word, the idea is to convert this letter to the uppercase and all the remaining letters before the next space ‘ ‘ or end of string to the lowercase. To do so, the ASCII Value of the characters need to be manipulated. If the character is a lowercase letter, we can convert it to uppercase using the ASCII value manipulation and vice-versa.

C++
// C++ Program to convert first character
// of word in a string to uppercase
#include <bits/stdc++.h>
using namespace std;

// Function to convert first character
// of word in a string to uppercase
string convert(string s) {
    for (int i = 0; i < s.length(); i++) {

        // If first character of a
        // word is found
        if ((s[i] != ' ') && (i == 0 || s[i - 1] == ' ')) {

            // If it is in lower-case
            // Convert into Upper-case
            if (s[i] >= 'a' && s[i] <= 'z') {
                s[i] = (char)(s[i] - 'a' + 'A');
            }
        }

        // If apart from first character
        // Any one is in Upper-case
        else if (s[i] >= 'A' && s[i] <= 'Z') {

            // Convert into Lower-Case
            s[i] = (char)(s[i] + 'a' - 'A');
        }
    }

    return s;
}

int main() {
    string s = "gEEks fOr GeeKs";
    cout<<convert(s);
    return 0;
}
C
// C Program to convert first character
// of word in a string to uppercase
#include <stdio.h>
#include <ctype.h>

// Function to convert first character
// of word in a string to uppercase
void convert(char *s) {

    for (int i = 0; s[i] != '\0'; i++) {

        // If first character of a word is found
        if ((s[i] != ' ') && (i == 0 || s[i - 1] == ' ')) {

            // If it is in lower-case
            // Convert into Upper-case
            if (s[i] >= 'a' && s[i] <= 'z') {
                s[i] = s[i] - 'a' + 'A';
            }
        } 

        // If apart from first character
        // Any one is in Upper-case
        else if (s[i] >= 'A' && s[i] <= 'Z') {

            // Convert into Lower-Case
            s[i] = s[i] + 'a' - 'A';
        }
    }
}

int main() {
    char s[] = "gEEks fOr GeeKs";
    convert(s);
    printf("%s", s);
    return 0;
}
Java
// Java Program to convert first character
// of word in a string to uppercase
class GfG {
    static String convert(String s){

        // Create a char array of given String
        char str[] = s.toCharArray();
        for (int i = 0; i < s.length(); i++) {

            // If first character of a word is found
            if ((str[i] != ' ') && (i == 0 || str[i - 1] == ' ')) {

                // If it is in lower-case
                // Convert into Upper-case
                if (str[i] >= 'a' && str[i] <= 'z') {
                    str[i] = (char)(str[i] - 'a' + 'A');
                }
            }

            // If apart from first character
            // Any one is in Upper-case
            else if (str[i] >= 'A' && str[i] <= 'Z') 

                // Convert into Lower-Case
                str[i] = (char)(str[i] + 'a' - 'A');            
        }

        // Convert the char array to equivalent String
        String res = new String(str);
        return res;
    }

    public static void main(String[] args) {
        String s = "gEEks fOr GeeKs";
        System.out.println(convert(s));
    }
}
Python
# Program to convert first character
# of word in a string to uppercase
def convert(s):
    str = list(s)
    
    for i in range(len(s)):
      
        # If first character of a word is found
        if (str[i] != ' ') and (i == 0 or s[i-1] == ' '):
          
            # If it is in lower-case
            # Convert into Upper-case
            if (str[i] >= 'a' and str[i] <= 'z'):
                str[i] = chr(ord(str[i]) - ord('a') + ord('A'))
        
        # If apart from first character
        # Any one is in Upper-case
        elif (str[i] >= 'A' and str[i] <= 'Z'):
          
            # Convert into Lower-Case
            str[i] = chr(ord(str[i]) + ord('a') - ord('A'))
    
    # Convert the char array 
    # to equivalent string
    res = "".join(str)       
    return res
    
if __name__ == "__main__":
    s = "gEEks fOr GeeKs"
    print(convert(s))
C#
// C# program to convert first character
// uppercase in a sentence
using System;

class GfG {
    static String convert(String s)  {

        // Create a char array of
        // given String
        char []str = s.ToCharArray();
        
        for (int i = 0; i < s.Length; i++)  {

            // If first character of a
            // word is found
            if ((s[i] != ' ') && (i == 0 || s[i - 1] == ' ')) {

                // If it is in lower-case
                // Convert into Upper-case
                if (str[i] >= 'a' && str[i] <= 'z')  {

                    str[i] = (char)(str[i] - 'a' + 'A');
                }
            }

            // If apart from first character
            // Any one is in Upper-case
            else if (str[i] >= 'A' && str[i] <= 'Z') 

                // Convert into Lower-Case
                str[i] = (char)(str[i] + 'a' - 'A');         
        }

        // Convert the char array to
        // equivalent String
        String res = new String(str);
        return res;
    }

    static void Main()  {
        String str = "gEEks fOr GeeKs";
        Console.Write(convert(str));
    }
}
JavaScript
// Javascript program to convert first character
// of word in a string to uppercase
    
function convert(s)  {

    // Create a char array of given String
    let ch = s.split("");
    for (let i = 0; i < s.length; i++) {

        // If first character of a word is found
        if ((s[i] != ' ') && (i == 0 || s[i - 1] == ' ')) {

            // If it is in lower-case
            // Convert into Upper-case
            if (ch[i] >= 'a' && ch[i] <= 'z') {

                ch[i] = String.fromCharCode(ch[i].charCodeAt(0) - 
                			'a'.charCodeAt(0) + 'A'.charCodeAt(0));
            }
        }

        // If apart from first character
        // Any one is in Upper-case
        else if (ch[i] >= 'A' && ch[i] <= 'Z')

            // Convert into Lower-Case
            ch[i] = String.fromCharCode(ch[i].charCodeAt(0) + 
            'a'.charCodeAt(0) - 'A'.charCodeAt(0));           
    }

    // Convert the char array to equivalent String
    let st = (ch).join("");
    return st;
}

let s = "gEEks fOr GeeKs";
console.log(convert(s));

Output
Geeks For Geeks


Article Tags :
Practice Tags :

Similar Reads