1
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.

4
  • 2
    don't use a regex. Iterate through all the chars, and append the current char, or its replacement, to a StringBuilder. You just need to increment a counter each time you make a replacement to point a the next element in the array. Commented Jan 31, 2014 at 20:11
  • Its troubling how you would get that result. Fundamentally, it should be a 1 to 1 replacement, not a replace all. Find and replace only 1 per itteration of string a's characters. Commented Jan 31, 2014 at 20:14
  • @JBNizet: That comment should be an answer, and I'd vote that up :-) Commented Jan 31, 2014 at 20:19
  • @FabianSteeg: I was hoping the OP would try something on his own, but he seems to just look for a ready-made solution. I'll leave him with the ones suggested here. Commented Jan 31, 2014 at 20:21

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1
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;
}

Comments

1
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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.