Dada una string, la tarea es reemplazar todos los espacios entre las palabras con un guión ‘-‘.
Ejemplos:
Input: str = "Geeks for Geeks." Output: Geeks-for-Geeks. Input: str = "A computer science portal for geeks" Output: A-computer-science-portal-for-geeks
Acercarse:
- Recorre toda la string carácter por carácter.
- Si el carácter es un espacio, reemplácelo con el guión ‘-‘.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to replace space with - #include <cstring> #include <iostream> using namespace std; int main() { // Get the String string str = "A computer science portal for geeks"; // Traverse the string character by character. for (int i = 0; i < str.length(); ++i) { // Changing the ith character // to '-' if it's a space. if (str[i] == ' ') { str[i] = '-'; } } // Print the modified string. cout << str << endl; return 0; }
Java
// Java program to replace space with - class GFG { // Function to replace Space with - static String replaceSpace(String str) { String s = ""; // Traverse the string character by character. for (int i = 0; i < str.length(); ++i) { // Changing the ith character // to '-' if it's a space. if (str.charAt(i) == ' ') s += '-'; else s += str.charAt(i); } // return the modified string. return s; } public static void main(String []args) { // Get the String String str = "A computer science portal for geeks"; System.out.println(replaceSpace(str)); } }
Python3
# Python 3 program to replace space with - # Driver Code if __name__ == '__main__': # Get the String str = "A computer science portal for geeks" # Traverse the string character by character. for i in range(0, len(str), 1): # Changing the ith character # to '-' if it's a space. if (str[i] == ' '): str = str.replace(str[i], '-') # Print the modified string. print(str) # This code is contributed by # Surendra_Gangwar
C#
// C# program to replace space with - using System; public class GFG { // Function to replace Space with - static String replaceSpace(String str) { String s = ""; // Traverse the string character by character. for (int i = 0; i < str.Length; ++i) { // Changing the ith character // to '-' if it's a space. if (str[i] == ' ') s += '-'; else s += str[i]; } // return the modified string. return s; } public static void Main() { // Get the String String str = "A computer science portal for geeks"; Console.Write(replaceSpace(str)); } } // This code is contributed by 29AjayKumar
PHP
<?php // PHP program to replace space with - // Get the String $str = "A computer science portal for geeks"; // Traverse the string character by character. for ($i = 0; $i < strlen($str); ++$i) { // Changing the ith character // to '-' if it's a space. if ($str[$i] == ' ') { $str[$i] = '-'; } } // Print the modified string. echo $str . "\n"; // This code is contributed // by Akanksha Rai
Javascript
<script> // JavaScript program to replace space with - // Get the String var str = "A computer science portal for geeks"; var newStr = str.split(""); // Traverse the string character by character. for (var i = 0; i < newStr.length; ++i) { // Changing the ith character // to '-' if it's a space. if (newStr[i] === " ") { newStr[i] = "-"; } } // Print the modified string. document.write(newStr.join("") + "<br>"); </script>
Producción:
A-computer-science-portal-for-geeks
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Método #2: Usar join() en Python:
- Como todas las palabras en una oración están separadas por espacios.
- Tenemos que dividir la oración por espacios usando split().
- Dividimos todas las palabras por espacios y las almacenamos en una lista.
- Únase a la lista usando ‘-‘ y guárdela en una string
- Imprime la string
A continuación se muestra la implementación del enfoque anterior:
Java
// Java implementation of the above approach import java.util.*; class GFG { static String printHyphen(String string) { // Split by space and converting // String to list and string = string.replace(' ', '-'); // returning the string return string; } // Driver code public static void main(String[] args) { String string = "Text contains malayalam and level words"; System.out.print(printHyphen(string)); } } // This code is contributed by gauravrajput1
Python3
# Python program for the above approach def printHyphen(string): # Split by space and converting # String to list and lis = list(string.split(" ")) # joining the list and storing in string string = '-'.join(lis) # returning the string return string # Driver code string = "Text contains malayalam and level words" print(printHyphen(string)) # This code is contributed by vikkycirus
Javascript
<script> // JavaScript program for the above approach function printHyphen(string){ // Split by space and converting // String to list and var lis = string.split(" ") // joining the list and storing in string string = lis.join("-"); // returning the string return string; } // Driver code var string = "Text contains malayalam and level words"; document.write(printHyphen(string)); </script>
Producción:
Text-contains-malayalam-and-level-words
Complejidad temporal: O(n)
Espacio auxiliar: O(n)
Método #3: Usar isspace() y replace() en python
Python3
# Python 3 program to replace space with - str = "A computer science portal for geeks" for i in str: if(i.isspace()): str=str.replace(i,"-") print(str)
Producción
A-computer-science-portal-for-geeks
Publicación traducida automáticamente
Artículo escrito por imdhruvgupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA