0

I have String of format something like this

String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";

I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this

String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";

How can I do it. I read Stringbuilder and String spilt, but now I am confused.

user2963317
  • 87
  • 1
  • 1
  • 7

2 Answers2

2

Something like:

StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
   builder.append(split).append("\n");
}

String output = builder.toString().trim();
Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
  • there is a slight change in my problem I want to insert newline after number succeeding by '.' like 1. and 2. and 3. – user2963317 Apr 28 '14 at 21:16
1

The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.

String temp = "";
for(int i=0; i<VIA.length(); i++) {
  if(Character.isDigit(VIA.charAt(i)))
    temp += "\n" + VIA.charAt(i);
  } else {
    temp += VIA.charAt(i);
  }
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.