TheBook
TheBook

Reputation: 1708

Split the right substring in a list

I am trying to store the line string in a list to process it. With the current state just the first element is being removed. I want to remove the letter substring from the line string before process it. How can I fix that?

I appreciate any help.

Simple:

stop 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16
Apple chair car 04:52 05:22 05:50 06:20 06:50 07:20 07:50 16:50 17:20 17:50 18:20 18:50 19:20

Result:

   [04:48, 05:18, 05:46, 06:16, 06:46, 07:16, 07:46, 16:46, 17:16, 17:46, 18:16, 18:46, 19:16]
   [04:52, 05:22, 05:50, 06:20, 06:50, 07:20, 07:50, 16:50, 17:20, 17:50, 18:20, 18:50, 19:20]

Code:

if (line.contains(":")) {
            String delims = " ";
            String[] tokens = line.split(delims);
            List<String> list = new ArrayList<String>(
                    Arrays.asList(tokens));
            list.remove(0);
            System.out.println(tokens);

        } 

Upvotes: 0

Views: 83

Answers (2)

John
John

Reputation: 5287

Here is an alternative without regex, end result will be string that you can split by space.

public class StringReplace {


public static void main(String[] args) {

    String output = replace("Apple chair car 04:52 05:22 05:50 06:20 06:50 07:20 07:50 16:50 17:20 17:50 18:20 18:50 19:20");

    List<String> tokens = new ArrayList<>();

    Collections.addAll(tokens, output.split(" "));          
}

private static String replace(String input) {

    char[] chars = input.toCharArray();

    StringBuilder builder = new StringBuilder();

    for (char character: chars) {

        // test against ASCII range 0 to ':' and 'space'
        if ((int)character > 47 && (int)(character) < 59 || (int)character == 32)  {

            builder.append(character);  
        }
    }

    return builder.toString().trim();

    }
}

Result >> 04:52 05:22 05:50 06:20 06:50 07:20 07:50 16:50 17:20 17:50 18:20 18:50 19:20

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

First replace and then do splitting.

string.replaceFirst("(?m)^.*?(?=\\d+:\\d+)", "").split("\\s+");

DEMO

  • string.replaceFirst("(?m)^.*?(?=\\d+:\\d+)", "") will replace the starting alphabets plus spaces with an empty string.

  • Now do splitting on spaces against the resultant string will give you the desired output.

Upvotes: 4

Related Questions