C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to replace the spaces of a string with a specific characterExplanationIn this program, we need to replace all the spaces present in the string with a specific character. String: Once in a blue moon String after replacing space with '-': Once-in-a-blue-moon One of the approach to accomplish this is by iterating through the string to find spaces. If spaces are present, then assign specific character in that index. Other approach is to use a built-in function replace function to replace space with a specific character. Algorithm
SolutionPythonstring = "Once in a blue moon"; ch = '-'; #Replace space with specific character ch string = string.replace(' ', ch); print("String after replacing spaces with given character: "); print(string); Output: String after replacing spaces with given character: Once-in-a-blue-moon C#include <stdio.h> #include <string.h> int main() { char string[] = "Once in a blue moon"; char ch = '-'; //Replace space with specific character ch for(int i = 0; i < strlen(string); i++){ if(string[i] == ' ') string[i] = ch; } printf("String after replacing spaces with given character: \n"); printf("%s", string); return 0; } Output: String after replacing spaces with given character: Once-in-a-blue-moon JAVApublic class ReplaceSpace { public static void main(String[] args) { String string = "Once in a blue moon"; char ch = '-'; //Replace space with specific character ch string = string.replace(' ', ch); System.out.println("String after replacing spaces with given character: "); System.out.println(string); } } Output: String after replacing spaces with given character: Once-in-a-blue-moon C#using System; public class ReplaceSpace { public static void Main() { String string1 = "Once in a blue moon"; char ch = '-'; //Replace space with specific character ch string1 = string1.Replace(' ', ch); Console.WriteLine("String after replacing spaces with given character: "); Console.WriteLine(string1); } } Output: String after replacing spaces with given character: Once-in-a-blue-moon PHP<!DOCTYPE html> <html> <body> <?php $string = "Once in a blue moon"; $ch = '-'; //Replace space with specific character ch $string = str_replace(' ', $ch, $string); print("String after replacing spaces with given character: <br>"); print($string); ?> </body> </html> Output: String after replacing spaces with given character: Once-in-a-blue-moon
Next Topic#
|