Reputation: 780
String name = "B R ER";
String[] a = {"U","G"};
For(int i= 0 ; i < a.length ; i++)
{
String temp = name.replaceAll("\\s",a[i]);
name = temp;
}
// But on result it shows BGRGER ... how to get result BURGER.
Upvotes: 1
Views: 75
Reputation: 1717
public static void main(String args[]) {
String name = "B R ER";
String temp = "";
String[] a = {"U","G"};
for (int i= 0 ; i < a.length ; i++) {
temp = name.replaceFirst("\\s",a[i]);
name = temp;
}
System.out.println(temp);
}
Upvotes: 1
Reputation: 346
String name = "B R ER";
String[] a = {"U","G"};
for(int i= 0 ; i < a.length ; i++)
{
String temp = name.replaceFirst("\\s",a[i]);
name = temp;
}
Upvotes: 1
Reputation: 784998
Instead of replaceAll
you can use replaceFirst
to replace only the first occurrence of regex but in this case you can totally avoid regex and use String methods like indexOf
, substring
etc to manipulate the output.
EDIT: Code as per comments:
String name = "B R ER";
String[] a = {"U","G"};
for(int i= 0 ; i < a.length ; i++) {
String temp = name.replaceFirst("\\s", a[i]);
name = temp;
}
System.out.println(name); // BURGER
Upvotes: 3