Escriba un programa Java para convertir el primer carácter en mayúsculas en una oración y, aparte del primer carácter, si algún otro carácter está en mayúsculas, ¿entonces convertirlo en minúsculas?
Ejemplos:
Input : gEEKs Output :Geeks Input :GFG Output :Gfg Input : GeeksforGeeks Output : Geeksforgeeks
Método 1:
C++
// C++ program to convert // first character uppercase // in a sentence #include<bits/stdc++.h> using namespace std; string convert(string str) { for (int i = 0; i < str.length(); i++) { // If first character of a // word is found if (i == 0 && str[i] != ' ' || str[i] != ' ' && str[i - 1] == ' ') { // If it is in lower-case if (str[i] >= 'a' && str[i] <= 'z') { // Convert into Upper-case 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'); } return str; } // Driver code int main() { string str = "gEEks fOr GeeKs"; cout << (convert(str)); return 0; } // This code is contributed by Chitranayal
Java
// Java program to convert first character // uppercase in a sentence class GFG { static String convert(String str) { // Create a char array of given String char ch[] = str.toCharArray(); for (int i = 0; i < str.length(); i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // 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] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to equivalent String String st = new String(ch); return st; } public static void main(String[] args) { String str = "gEEks fOr GeeKs"; System.out.println(convert(str)); } }
Python3
# Python3 program to convert first character # uppercase in a sentence def convert(s): # Create a char array of # given string ch = list(s) for i in range(len(s)): # If first character of a word is found if (i == 0 and ch[i] != ' ' or ch[i] != ' ' and ch[i - 1] == ' '): # If it is in lower-case if (ch[i] >= 'a' and ch[i] <= 'z'): # Convert into Upper-case ch[i] = chr(ord(ch[i]) - ord('a') + ord('A')) # If apart from first character # Any one is in Upper-case elif (ch[i] >= 'A' and ch[i] <= 'Z'): # Convert into Lower-Case ch[i] = chr(ord(ch[i]) + ord('a') - ord('A')) # Convert the char array # to equivalent string st = "".join(ch) return st; # Driver code if __name__=="__main__": s = "gEEks fOr GeeKs" print(convert(s)); # This code is contributed by rutvik_56
C#
// C# program to convert first character // uppercase in a sentence using System; class GFG { static String convert(String str) { // Create a char array of // given String char []ch = str.ToCharArray(); for (int i = 0; i < str.Length; i++) { // If first character of a // word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // 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] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to // equivalent String String st = new String(ch); return st; } // Driver code public static void Main() { String str = "gEEks fOr GeeKs"; Console.Write(convert(str)); } } // This code is contributed by Nitin Mittal.
Javascript
<script> // Javascript program to convert first character // uppercase in a sentence function convert(str) { // Create a char array of given String let ch = str.split(""); for (let i = 0; i < str.length; i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case 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 str = "gEEks fOr GeeKs"; document.write(convert(str)); // This code is contributed by avanitrachhadiya2155 </script>
Producción:
Geeks For Geeks
Complejidad de tiempo : O(n), donde n es la longitud de la oración dada.
Espacio auxiliar: O(1)
Método 2: Uso de métodos incorporados de Java
Para poner en mayúsculas cada palabra, llame al método toLowerCase() para poner la string en formato de minúsculas. Repita la string, si se encuentra algún espacio en la iteración anterior y el elemento actual no es un espacio, llame al método toUpperCase() para poner la primera letra de la palabra en formato mayúscula y agregue la string en el búfer.
A continuación se muestra la implementación:
Java
// Java Program to capitalize each word in a string public class GFG { // Method to convert the string static String capitailizeWord(String str) { StringBuffer s = 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 < str.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 == ' ' && str.charAt(i) != ' ') s.append(Character.toUpperCase(str.charAt(i))); else s.append(str.charAt(i)); ch = str.charAt(i); } // Return the string with trimming return s.toString().trim(); } // Driver Code public static void main(String args[]) { // Declare the string String s1 = "gEEks fOr GeeKs"; // Convert that string into lowercase s1 = s1.toLowerCase(); // Call the method to capitalize each word System.out.println(capitailizeWord(s1)); } }
Complejidad del tiempo : O(n)
Espacio Auxiliar: O(n)
Método 3: Usando Python3
Enfoque: podemos crear una lista de todas las palabras en una oración (digamos string_array). Después de crear string_array, si trabajamos directamente en esa lista e intentamos cambiar los caracteres iniciales en minúsculas de las palabras, obtendremos un error » El objeto ‘str’ no admite la asignación de elementos «. Para evitar esto, podemos crear una lista de valores ASCII (por ejemplo, ascii_array) de caracteres correspondientes a los caracteres de string_array.
Podemos trabajar fácilmente con ascii_array y convertir los caracteres iniciales en minúsculas de las palabras en mayúsculas simplemente restando 32 de su valor ASCII. Después de cambiar los valores en ascii_array, convertimos cada valor ASCII en ascii_array a sus caracteres correspondientes usando la función chr() . La función chr() devuelve el carácter correspondiente al valor ASCII pasado en los parámetros. De esta forma obtendremos una lista de strings en mayúsculas.
A continuación se muestra la implementación del enfoque anterior.
Python3
# Python program to capitalize the # first character of each word in a sentence # Function definition def solve (st): ascii_array = [] # creating a list of ascii values # of all the characters in the sentence for i in range (0, len (st)): ascii_array.append (ord (st[i])) # check if the first character of # each word is a lowercase character. # To convert a lowercase character to an # uppercase character, we subtract 32 from # the ASCII value of lowercase character. if ascii_array[0] >= 97 and ascii_array[0] <= 122 : ascii_array[0] = ascii_array[0] - 32 # create an empty list which will store # the characters corresponding to the # ascii values in ascii_array newlist = [] newlist.append (chr (ascii_array[0])) for i in range (1, len (ascii_array)): # 32 is the ascii value for 'space' or ' '. # so we use this condition to check for # the next word in the sentence # as in a sentence we have space separated words if ascii_array[i] == 32: if ascii_array[i + 1] >= 97 and ascii_array[i+1] <= 122: ascii_array[i + 1] = ascii_array[i+1] - 32 newlist.append (chr (ascii_array[i])) # in the end, we return a string after # joining the values obtained in newlist return (''.join (newlist)) # Driver Code string = 'geeks for geeks' result = solve (string) print (result) # This code is contributed by Kishan Mishra
Geeks For Geeks
Complejidad del tiempo : O(n)
Espacio Auxiliar: O(n)
Publicación traducida automáticamente
Artículo escrito por Bishal Kumar Dubey y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA