Convierta una array de strings dada en una oración de formato Camel Case

Dada una array arr[] de N strings , cada una de las cuales contiene palabras con alfabetos ingleses en mayúsculas o minúsculas , la tarea es crear una oración en formato Camel Case usándolas.

Ejemplo:

Entrada: arr[] = {“AnNiruddHA Routh”, “LOVES”, “to”, “COdE everyDAY””}
Salida: AniruddhaRouth Loves To Code Everyday
Explicación: La oración anterior es la oración combinada de todas las palabras en el orden dado en Camel Case.

Entrada: arr[] = {“I”, “GOT”, “iNtErN”, “at geekSforgeekS”}
Salida: Obtuve una pasantía en Geeksforgeeks

 

Enfoque: el problema dado se puede resolver recorriendo cada palabra una por una e insertando cada carácter en el formato de mayúsculas y minúsculas Camel en una string resultante, como se muestra en los pasos a continuación: 

  • Cree una string vacía para almacenar la string resultante
  • Recorra la array de strings palabra por palabra, y para cada palabra: 
    • Si el carácter está en el primer índice, inserte el carácter actual en formato de mayúsculas
    • De lo contrario, inserte todos los demás caracteres en formato de minúsculas
    • Siempre que termine una palabra, agregue un espacio a la string, excepto por la última palabra (inserte un punto en este caso).
  • Devuelve la string resultante al final.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert the given array
// of strings into a sentence in the
// Camel Case formatting
string convertCase(vector<string> arr, int N)
{
    // Stores the final sentence
    string ans = "";
 
    // Loop to iterate over the array
    for (int i = 0; i < N; i++) {
 
        // If the current word is not the 1st
        // word, insert space
        if (ans.size() > 0) {
            ans += ' ';
        }
 
        // Insert the first character of arr[i]
        ans += toupper(arr[i][0]);
 
        // Loop to iterate over current array element
        for (int j = 1; j < arr[i].size(); j++) {
 
            // If a space is found,
            // the next character
            // should be in upper case
            if (arr[i][j] == ' ') {
                ans += ' ';
                ans += toupper(arr[i][j + 1]);
                j++;
            }
 
            // Otherwise the characters
            // must be in the lower case
            else {
                ans += tolower(arr[i][j]);
            }
        }
    }
 
    // Return Answer
    return ans;
}
 
// Driver program
int main()
{
    vector<string> arr{
        "AnNiruddHA Routh",
        "LOVES", "to",
        "COdE everyDAY"
    };
    int N = arr.size();
 
    cout << convertCase(arr, N);
 
    return 0;
}

Java

// Java code for the above approach
import java.util.*;
 
class GFG{
 
// Function to convert the given array
// of strings into a sentence in the
// Camel Case formatting
static String convertCase(String[] arr, int N)
{
     
    // Stores the final sentence
    String ans = "";
 
    // Loop to iterate over the array
    for(int i = 0; i < N; i++)
    {
         
        // If the current word is not the 1st
        // word, insert space
        if (ans.length() > 0)
        {
            ans += ' ';
        }
 
        // Insert the first character of arr[i]
        ans += Character.toUpperCase(arr[i].charAt(0));
 
        // Loop to iterate over current array element
        for(int j = 1; j < arr[i].length(); j++)
        {
             
            // If a space is found,
            // the next character
            // should be in upper case
            if (arr[i].charAt(j) == ' ')
            {
                ans += ' ';
                char t = Character.toUpperCase(
                    arr[i].charAt(j + 1));
                ans += t;
                j++;
            }
 
            // Otherwise the characters
            // must be in the lower case
            else
            {
                ans += Character.toLowerCase(
                    arr[i].charAt(j));
            }
        }
    }
 
    // Return Answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String[] arr = { "AnNiruddHA Routh", "LOVES", "to",
                     "COdE everyDAY" };
    int N = arr.length;
 
    System.out.println(convertCase(arr, N));
}
}
 
// This code is contributed by Potta Lokesh

Python3

# Python3 program of the above approach
 
# Function to convert the given array
# of strings into a sentence in the
# Camel Case formatting
def convertCase(arr, N) :
     
    # Stores the final sentence
    ans = "";
 
    # Loop to iterate over the array
    for i in range(N) :
 
        # If the current word is not the 1st
        # word, insert space
        if (len(ans) > 0) :
            ans += ' ';
 
        # Insert the first character of arr[i]
        ans += arr[i][0].upper();
     
        j = 1
         
        # Loop to iterate over current array element
        while j < len(arr[i]) :
             
            # If a space is found,
            # the next character
            # should be in upper case
            if (arr[i][j] == ' ') :
                ans += ' ';
                ans += arr[i][j + 1].upper();
                j += 1;
 
            # Otherwise the characters
            # must be in the lower case
            else :
                ans += arr[i][j].lower();
             
            j += 1;
 
    # Return Answer
    return ans;
 
# Driver program
if __name__ == "__main__" :
 
    arr = ["AnNiruddHA Routh","LOVES", "to","COdE everyDAY"]
    N = len(arr);
    print(convertCase(arr, N));
 
    # This code is contributed by AnkThon

C#

// C# code for the above approach
using System;
 
class GFG
{
 
    // Function to convert the given array
    // of strings into a sentence in the
    // Camel Case formatting
    static String convertCase(String[] arr, int N)
    {
 
        // Stores the final sentence
        String ans = "";
 
        // Loop to iterate over the array
        for (int i = 0; i < N; i++)
        {
 
            // If the current word is not the 1st
            // word, insert space
            if (ans.Length > 0)
            {
                ans += ' ';
            }
 
            // Insert the first character of arr[i]
            ans += char.ToUpper(arr[i][0]);
 
            // Loop to iterate over current array element
            for (int j = 1; j < arr[i].Length; j++)
            {
 
                // If a space is found,
                // the next character
                // should be in upper case
                if (arr[i][j] == ' ')
                {
                    ans += ' ';
                    char t = char.ToUpper(arr[i][j + 1]);
                    ans += t;
                    j++;
                }
 
                // Otherwise the characters
                // must be in the lower case
                else
                {
                    ans += char.ToLower(arr[i][j]);
                }
            }
        }
 
        // Return Answer
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        String[] arr = { "AnNiruddHA Routh", "LOVES", "to",
                     "COdE everyDAY" };
        int N = arr.Length;
 
        Console.Write(convertCase(arr, N));
    }
}
 
// This code is contributed by gfgking

Javascript

<script>
    // JavaScript program of the above approach
 
    // Function to convert the given array
    // of strings into a sentence in the
    // Camel Case formatting
    const convertCase = (arr, N) => {
        // Stores the final sentence
        let ans = "";
 
        // Loop to iterate over the array
        for (let i = 0; i < N; i++) {
 
            // If the current word is not the 1st
            // word, insert space
            if (ans.length > 0) {
                ans += ' ';
            }
 
            // Insert the first character of arr[i]
            ans += (arr[i][0]).toUpperCase();
 
            // Loop to iterate over current array element
            for (let j = 1; j < arr[i].length; j++) {
 
                // If a space is found,
                // the next character
                // should be in upper case
                if (arr[i][j] == ' ') {
                    ans += ' ';
                    ans += (arr[i][j + 1]).toUpperCase();
                    j++;
                }
 
                // Otherwise the characters
                // must be in the lower case
                else {
                    ans += (arr[i][j]).toLowerCase();
                }
            }
        }
 
        // Return Answer
        return ans;
    }
 
    // Driver program
 
    let arr = [
        "AnNiruddHA Routh",
        "LOVES", "to",
        "COdE everyDAY"
    ];
    let N = arr.length;
 
    document.write(convertCase(arr, N));
 
// This code is contributed by rakeshsahni
 
</script>
Producción

Anniruddha Routh Loves To Code Everyday

Complejidad de tiempo : O(N*M), donde M es la longitud promedio de una string sobre todas las strings dadas
Espacio auxiliar: O(N*M)

Publicación traducida automáticamente

Artículo escrito por aniruddharouth y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *