Zach Sugano
Zach Sugano

Reputation: 1607

Java split strings at specific points

I am trying to take user inputted text and split it into an array of strings. The user is supposed to enter the line break in the form of "%n". How do I get it to split the string at that point?

Upvotes: 0

Views: 1259

Answers (6)

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

public String[] split(String regex, int limit)

or

public String[] split(String regex)

Upvotes: 0

Vladimir
Vladimir

Reputation: 10493

Please, take a look at documentation on String.split first. It can be used the following way:

public class Main {
  public static void main(String... args) {
    for (String line : "aaa%nbbb%nccc".split("%n")) {
      System.out.println(line);
    }
  }
}

Will give you:

aaa
bbb
ccc

Upvotes: 1

Senthil Kumar
Senthil Kumar

Reputation: 10255

Using String's split method like this.

String input = "abcd%nefgh%nijkl";
String[] inputSplitted = input.split("%n");
System.out.println(Arrays.toString(inputSplitted));

Output: [abcd, efgh, ijkl]

Upvotes: 1

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

str.substring(startIndex,endIndex);

Or

String lines[]=input.split("\n");

Upvotes: 1

juergen d
juergen d

Reputation: 204746

String[] lines = yourString.split("%n");

Upvotes: 3

Vic
Vic

Reputation: 1888

If you are sure, that the line break will be "\n", there should be nothing special with it. Have you tried the String.split(...) method?

By the way, there were a lot of discussions on this topic.

Upvotes: 1

Related Questions