skip to Main Content
String text = "test_123
check_1  123  
test_1
ASD@#$
qwer #$%^
test   1
this is book";

and turn it into a string array like:

{"test_123","check_1  123","test_1","ASD@#$","qwer #$%^","test   1","this is book"}

4

Answers


  1. The split function is what will help you to achieve this, you’ll have to identify a pattern, which is a regular expression, that work as the split rule.

    From what I see the String text doesn’t have an intuitive pattern

    Login or Signup to reply.
  2. If you want single elements, you can do this:

    List<String> myList = List.of(text.split(" "));
    

    However, like someone pointed out, there’s no recognizable pattern in what you wanna do. You can try some weird regex inside the split but I doubt it’ll work.

    EDIT: If you add n at the end of each block of text/string it will work. Example:

      String text = "test_123n check_1 123n test_1n ASD@#$n qwer #$%^n test  1n this is bookn";
        List<String> myList = List.of(text.split("n"));
    

    This should do the trick

    Login or Signup to reply.
  3. There are a few ways to achieve this.

    You can use the String#split method, which uses a regular expression pattern as the argument.

    The following should suffice in identifying the new-line delimiter.

    rn?|n
    
    String[] strings = text.split("\r\n?|\n");
    

    Additionally, you could use the BufferedReader and StringReader classes.

    BufferedReader reader = new BufferedReader(new StringReader(text));
    String[] strings = reader.lines().toList().toArray(new String[0]);
    reader.close();
    

    Similarly, you could use the Scanner class.

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\r\n?|\n");
    String[] strings = scanner.tokens().toList().toArray(new String[0]);
    scanner.close();
    

    All of these methods will output the following.

    [test_123, check_1  123, test_1, ASD@#$, qwer #$%^, test   1, this is book]
    
    Login or Signup to reply.
  4. You can use String.split method. Regular expressions can be used to define delimiter. For example:

        String newLine = "n";
        
        String str = String.join(newLine, "test_123", 
        "check_1  123", 
        "test_1", 
        "ASD@#$", 
        "qwer #$%^", 
        "test   1", 
        "this is book");
    
    
        String[] splitted = str.split("\s+|\n+");
        
        for (int i = 0; i < splitted.length; i++) {
            System.out.println(splitted[i]);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search