Azfaar kabir Siddiqui
Azfaar kabir Siddiqui

Reputation: 780

how to replace space one by one using regex in java?

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

Answers (3)

Girish
Girish

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

Stephen Corcoran
Stephen Corcoran

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

anubhava
anubhava

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

Related Questions