Given a string, the task is to replace all spaces between words with a hyphen "-".
Examples:
Input: str = "Geeks for Geeks." Output: Geeks-for-Geeks. Input: str = "A computer science portal for geeks" Output: A-computer-science-portal-for-geeks
Approach:
// 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)); } }
Output:
A-computer-science-portal-for-geeks
Time Complexity: O(N)
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.