Reputation: 11
I have a really long text that looks like "123testes1233iambeginnerplshelp123 .." and I need to separate the line with the paragraph each time the program reads number. So output should be like:
123tests
12333iambeninnerplshelp
123 ...
Upvotes: 1
Views: 369
Reputation: 440
my solution
public StringSplitNum(){
String someString = "123testes1233iambeginnerplshelp123abc";
String regex = "((?<=[a-zA-Z])(?=[0-9]))|((?<=[0-9])(?=[a-zA-Z]))";
List arr = Arrays.asList(someString.split(regex));
for(int i=0; i< arr.size();i+=2){
System.out.println(arr.get(i)+ " " + arr.get(i+1));
}
Upvotes: 0
Reputation: 3158
A simple approach (without any dependencies) would look something like this,
class Test {
public static void main (String[] args) throws java.lang.Exception
{
String a = "123testes1233iambeginnerplshelp123";
StringBuffer sb = new StringBuffer();
for (int i=0; i<a.length()-1; i++) {
while (i<a.length()-1 && !(!isNumber(a.charAt(i)) && isNumber(a.charAt(i+1)))) {
sb.append(a.substring(i,i+1));
i++;
}
sb.append(a.substring(i,i+1));
System.out.println(sb.toString());
sb.setLength(0);
}
}
private static boolean isNumber (char c) {
return ((int)c >=48) && ((int)c <= 57);
}
}
Upvotes: 1
Reputation: 2892
You can solve it using Regex. Everytime we are looking for patterns where number is followed by characters and if it is found, print it:
String text = "123testes1233stackoverflowwillsaveyou123dontworry";
String wordToFind = "\\d+[a-z]+";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println(match.group());
}
Upvotes: 4
Reputation: 44932
One way to do it would be to use StringTokenizer
. If you make the assumption that every output line must start with 123
, even if the input doesn't start with it, it could be:
String input = "123testes1233iambeginnerplshelp123 ..";
String delimiter = "123";
StringTokenizer tokenizer = new StringTokenizer(input, delimiter);
while (tokenizer.hasMoreTokens()) {
String line = delimiter + tokenizer.nextToken();
System.out.println(line);
}
Upvotes: 2