Reputation: 21
I have this long string "Ab1ac2axd3nxn70-00-0-0" For the life of me I cannot figure out how to separate that string in java to look like this. "Ab1 ac2 axd3 nxn7 0-0 0-0-0" I am thinking I need to use delimiters but I don't know the code for the desired format I want and also don't know how to correctly write it.
It might help to know that zeros will only occur as the form "0-0" or "0-0-0" if it is attached to letters it will only be like this ab30-0 now I don't want to put spaces between the dashes and the zeros but if this occurs"0-00-0-0" I want it to be formatted like this "0-0 0-0-0"
Upvotes: 0
Views: 297
Reputation: 3392
This will solve your problem. There may be a more elegant solution, but this definitely works:
public class Delimiter {
public static void main(String[] args) {
String input = "Ab1ac2axd3nxn70-00-0-0";
int l = input.length() - 1;
char[] inputChars = input.toCharArray();
StringBuilder output = new StringBuilder();
for (int i = 0; i < l; i++) {
char c = inputChars[i];
output.append(c);
if (Character.isDigit(c) && inputChars[i+1] != '-')
output.append(' ');
}
output.append(inputChars[l]);
System.out.println(output.toString());
}
}
Upvotes: 1