Java Program to replace the spaces of a string with a specific character
In this program, we need to replace all the spaces present in the string with a specific character.
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.
string 1
"This Is a Comman Name"
string 2
"This-Is-a-Comman-Name"
Class
Program
class Replace_space_char {
public static void main(String[] args) {
//declare string
String str1="This Is a Comman Name";
char ch = '-';
str=str.replace(' ',ch);
System.out.println(str);
}
}
output
This-Is-a-Comman-Name
Theory
In this program in main task in white space is replace by specific char in given string . fisrt of all declare the string and which char is replace is declare in ch variacle .
then we are used to replace() method to easy replace specific char by specific char is main use of replace() method in string. then finally print string to replace white space with specific char.
No comments:
Post a Comment