1913

I want to split the string "004-034556" into two strings by the delimiter "-":

part1 = "004";
part2 = "034556";

That means the first string will contain the characters before '-', and the second string will contain the characters after '-'.

I also want to check if the string has '-' in it.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
riyana
  • 21,385
  • 10
  • 35
  • 34

38 Answers38

3359

Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
89

An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class SplitExample
{
    private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");

    public static void checkString(String s)
    {
        Matcher m = twopart.matcher(s);
        if (m.matches()) {
            System.out.println(s + " matches; first part is " + m.group(1) +
                               ", second part is " + m.group(2) + ".");
        } else {
            System.out.println(s + " does not match.");
        }
    }

    public static void main(String[] args) {
        checkString("123-4567");
        checkString("foo-bar");
        checkString("123-");
        checkString("-4567");
        checkString("123-4567-890");
    }
}

As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:

(\d+)-(\d+)

The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:

([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
([^-]+)-([^-]+)            // Each part consists of characters other than -
([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                           // the second consists of digits
Rob Hague
  • 1,409
  • 9
  • 14
  • This is a great solution, however the first part should be `m.group(1)`, the second part `m.group(2)`, since `m.group(0)` actually returns the full matching pattern. I think i also remember `group(0)` used to be the first match instead of the full pattern, maybe this changed in a recent java version update. – ptstone Jul 13 '17 at 04:28
50

Use:

String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");

This will split your string into two parts. The first element in the array will be the part containing the stuff before the -, and the second element in the array will contain the part of your string after the -.

If the array length is not 2, then the string was not in the format: string-string.

Check out the split() method in the String class.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • 6
    This will accept "-555" as input and returns [, 555]. The requirements aren't defined that clear, if it would be valid to accept this. I recommend writing some unit-tests to define the desired behaviour. – Michael Konietzka Aug 14 '10 at 06:36
  • 1
    Probly safest to change (result.length != 2) to (result.length < 2) – Uncle Iroh Feb 10 '14 at 16:53
38

This:

String[] out = string.split("-");

should do the thing you want. The string class has many method to operate with a string.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
secmask
  • 7,649
  • 5
  • 35
  • 52
31
// This leaves the regexes issue out of question
// But we must remember that each character in the Delimiter String is treated
// like a single delimiter        

public static String[] SplitUsingTokenizer(String subject, String delimiters) {
   StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
   ArrayList<String> arrLis = new ArrayList<String>(subject.length());

   while(strTkn.hasMoreTokens())
      arrLis.add(strTkn.nextToken());

   return arrLis.toArray(new String[0]);
}
Nicolas
  • 472
  • 6
  • 14
Mnyikka
  • 1,223
  • 17
  • 12
  • 64
    The JavaDoc clearly states: *"`StringTokenizer` is a legacy class that is retained for compatibility reasons although **its use is discouraged in new code**. It is recommended that anyone seeking this functionality use the `split` method of `String` or the `java.util.regex` package instead."* – bvdb Sep 09 '13 at 07:07
27

With Java 8:

    List<String> stringList = Pattern.compile("-")
            .splitAsStream("004-034556")
            .collect(Collectors.toList());

    stringList.forEach(s -> System.out.println(s));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Somaiah Kumbera
  • 7,063
  • 4
  • 43
  • 44
21

Use org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.

Method signature:

public static String[] split(String str, char separatorChar);

In your case, you want to split a string when there is a "-".

You can simply do as follows:

String str = "004-034556";

String split[] = StringUtils.split(str,"-");

Output:

004
034556

Assume that if - does not exists in your string, it returns the given string, and you will not get any exception.

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
sandeep vanama
  • 689
  • 8
  • 8
20

To summarize: there are at least five ways to split a string in Java:

  1. String.split():

     String[] parts ="10,20".split(",");
    
  2. Pattern.compile(regexp).splitAsStream(input):

     List<String> strings = Pattern.compile("\\|")
           .splitAsStream("010|020202")
           .collect(Collectors.toList());
    
  3. StringTokenizer (legacy class):

     StringTokenizer strings = new StringTokenizer("Welcome to EXPLAINJAVA.COM!", ".");
     while(strings.hasMoreTokens()){
         String substring = strings.nextToken();
         System.out.println(substring);
     }
    
  4. Google Guava Splitter:

     Iterable<String> result = Splitter.on(",").split("1,2,3,4");
    
  5. Apache Commons StringUtils:

     String[] strings = StringUtils.split("1,2,3,4", ",");
    

So you can choose the best option for you depending on what you need, e.g. return type (array, list, or iterable).

Here is a big overview of these methods and the most common examples (how to split by dot, slash, question mark, etc.)

19

The requirements left room for interpretation. I recommend writing a method,

public final static String[] mySplit(final String s)

which encapsulate this function. Of course you can use String.split(..) as mentioned in the other answers for the implementation.

You should write some unit-tests for input strings and the desired results and behaviour.

Good test candidates should include:

 - "0022-3333"
 - "-"
 - "5555-"
 - "-333"
 - "3344-"
 - "--"
 - ""
 - "553535"
 - "333-333-33"
 - "222--222"
 - "222--"
 - "--4555"

With defining the according test results, you can specify the behaviour.

For example, if "-333" should return in [,333] or if it is an error. Can "333-333-33" be separated in [333,333-33] or [333-333,33] or is it an error? And so on.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Konietzka
  • 5,419
  • 2
  • 28
  • 29
  • 5
    Useful advice, but not actually an answer to the question. If you're supporting another answer's with detail a comment is preferred. – Chris Mountford Aug 24 '14 at 22:43
  • Use : split ( String regex, int limit ) and NOT split( String regex) for reference visit https://www.geeksforgeeks.org/split-string-java-examples/ – Ryan Augustine Sep 20 '18 at 11:02
17

You can try like this also

 String concatenated_String="hi^Hello";

 String split_string_array[]=concatenated_String.split("\\^");
17

Assuming, that

  • you don't really need regular expressions for your split
  • you happen to already use apache commons lang in your app

The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.

eis
  • 51,991
  • 13
  • 150
  • 199
16

For simple use cases String.split() should do the job. If you use guava, there is also a Splitter class which allows chaining of different string operations and supports CharMatcher:

Splitter.on('-')
       .trimResults()
       .omitEmptyStrings()
       .split(string);
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
13

The fastest way, which also consumes the least resource could be:

String s = "abc-def";
int p = s.indexOf('-');
if (p >= 0) {
    String left = s.substring(0, p);
    String right = s.substring(p + 1);
} else {
  // s does not contain '-'
}
David
  • 435
  • 5
  • 7
  • 7
    The most scarce resource is often programmer's time and attention. This code consumes more of that resource than alternatives. – Chris Mountford Aug 24 '14 at 22:45
  • you have a lot of built-in resources that you can use, where the performance it's really considered, this solution is lacking of performance execution time – J Sanchez Apr 22 '16 at 16:50
  • 1
    To do a simple split on a single character with error checking, this is no more complex than the regex version. – tekHedd Jan 16 '19 at 21:13
  • Bravo! Finally an answer to this question that does not use regex! Using a regex for this simple task is rather a headscratcher. Good to see there are sane programmers still on this earth :-) – Gabriel Magana Mar 22 '19 at 01:44
  • *There is only one "-", an Exception is wanted and the result should go to string1 and string2.* Make `string1 = s.substring(0, s.indexOf("-"));` `string2 = s.substring(s.indexOf("-") + 1);` out of it. You will get the `StringIndexOutOfBoundsException` automatically if there was no "-". – Kaplan Apr 17 '20 at 13:53
12

String Split with multiple characters using Regex

public class StringSplitTest {
     public static void main(String args[]) {
        String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
        //String[] strs = s.split("[,\\s\\;]");
        String[] strs = s.split("[,\\;]");
        System.out.println("Substrings length:"+strs.length);
        for (int i=0; i < strs.length; i++) {
            System.out.println("Str["+i+"]:"+strs[i]);
        }
     }
  }

Output:

Substrings length:17
Str[0]:
Str[1]:String
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[7]:
Str[8]:String
Str[9]:String
Str[10]: String
Str[11]: String
Str[12]:
Str[13]:String
Str[14]:String
Str[15]:String
Str[16]:String

But do not expect the same output across all JDK versions. I have seen one bug which exists in some JDK versions where the first null string has been ignored. This bug is not present in the latest JDK version, but it exists in some versions between JDK 1.7 late versions and 1.8 early versions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
12

There are only two methods you really need to consider.

Use String.split for a one-character delimiter or you don't care about performance

If performance is not an issue, or if the delimiter is a single character that is not a regular expression special character (i.e., not one of .$|()[{^?*+\) then you can use String.split.

String[] results = input.split(",");

The split method has an optimization to avoid using a regular expression if the delimeter is a single character and not in the above list. Otherwise, it has to compile a regular expression, and this is not ideal.

Use Pattern.split and precompile the pattern if using a complex delimiter and you care about performance.

If performance is an issue, and your delimiter is not one of the above, you should pre-compile a regular expression pattern which you can then reuse.

// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");

/// ... later
String[] results = pattern.split(input);

This last option still creates a new Matcher object. You can also cache this object and reset it for each input for maximum performance, but that is somewhat more complicated and not thread-safe.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rghome
  • 8,529
  • 8
  • 43
  • 62
11
public class SplitTest {

    public static String[] split(String text, String delimiter) {
        java.util.List<String> parts = new java.util.ArrayList<String>();

        text += delimiter;

        for (int i = text.indexOf(delimiter), j=0; i != -1;) {
            String temp = text.substring(j,i);
            if(temp.trim().length() != 0) {
                parts.add(temp);
            }
            j = i + delimiter.length();
            i = text.indexOf(delimiter,j);
        }

        return parts.toArray(new String[0]);
    }


    public static void main(String[] args) {
        String str = "004-034556";
        String delimiter = "-";
        String result[] = split(str, delimiter);
        for(String s:result)
            System.out.println(s);
    }
}
Akhilesh Dhar Dubey
  • 2,152
  • 2
  • 25
  • 39
11

You can split a string by a line break by using the following statement:

String textStr[] = yourString.split("\\r?\\n");

You can split a string by a hyphen/character by using the following statement:

String textStr[] = yourString.split("-");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
9

Please don't use StringTokenizer class as it is a legacy class that is retained for compatibility reasons, and its use is discouraged in new code. And we can make use of the split method as suggested by others as well.

String[] sampleTokens = "004-034556".split("-");
System.out.println(Arrays.toString(sampleTokens));

And as expected it will print:

[004, 034556]

In this answer I also want to point out one change that has taken place for split method in Java 8. The String#split() method makes use of Pattern.split, and now it will remove empty strings at the start of the result array. Notice this change in documentation for Java 8:

When there is a positive-width match at the beginning of the input sequence then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

It means for the following example:

String[] sampleTokensAgain = "004".split("");
System.out.println(Arrays.toString(sampleTokensAgain));

we will get three strings: [0, 0, 4] and not four as was the case in Java 7 and before. Also check this similar question.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
8

One way to do this is to run through the String in a for-each loop and use the required split character.

public class StringSplitTest {

    public static void main(String[] arg){
        String str = "004-034556";
        String split[] = str.split("-");
        System.out.println("The split parts of the String are");
        for(String s:split)
        System.out.println(s);
    }
}

Output:

The split parts of the String are:
004
034556
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Keshav Pradeep Ramanath
  • 1,623
  • 4
  • 24
  • 33
8
import java.io.*;

public class BreakString {

  public static void main(String args[]) {

    String string = "004-034556-1234-2341";
    String[] parts = string.split("-");

    for(int i=0;i<parts.length;i++) {
      System.out.println(parts[i]);
    }
  }
}
L Joey
  • 155
  • 2
  • 8
Ravi Pandey
  • 424
  • 4
  • 5
  • 4
    if i may share advice, how your answer brings more value than the already accepted solution? http://stackoverflow.com/a/3481842/420096 on such situations you may cast vote on the existing solution, specially if this is a clear trivial case like that one. – Sombriks Oct 02 '16 at 03:51
8

You can use Split():

import java.io.*;

public class Splitting
{

    public static void main(String args[])
    {
        String Str = new String("004-034556");
        String[] SplittoArray = Str.split("-");
        String string1 = SplittoArray[0];
        String string2 = SplittoArray[1];
    }
}

Else, you can use StringTokenizer:

import java.util.*;
public class Splitting
{
    public static void main(String[] args)
    {
        StringTokenizer Str = new StringTokenizer("004-034556");
        String string1 = Str.nextToken("-");
        String string2 = Str.nextToken("-");
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarat Chandra
  • 5,636
  • 34
  • 30
7

Here are two ways two achieve it.

WAY 1: As you have to split two numbers by a special character you can use regex

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TrialClass
{
    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("[0-9]+");
        Matcher m = p.matcher("004-034556");

        while(m.find())
        {
            System.out.println(m.group());
        }
    }
}

WAY 2: Using the string split method

public class TrialClass
{
    public static void main(String[] args)
    {
        String temp = "004-034556";
        String [] arrString = temp.split("-");
        for(String splitString:arrString)
        {
            System.out.println(splitString);
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Akshay Gaikwad
  • 420
  • 6
  • 13
6

You can simply use StringTokenizer to split a string in two or more parts whether there are any type of delimiters:

StringTokenizer st = new StringTokenizer("004-034556", "-");
while(st.hasMoreTokens())
{
    System.out.println(st.nextToken());
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rohit-Pandey
  • 2,039
  • 17
  • 24
4

Check out the split() method in the String class on javadoc.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

String data = "004-034556-1212-232-232";
int cnt = 1;
for (String item : data.split("-")) {
        System.out.println("string "+cnt+" = "+item);
        cnt++;
}

Here many examples for split string but I little code optimized.

RubioRic
  • 2,442
  • 4
  • 28
  • 35
Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
4
String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter

string1=004 // sTemp[0];
string2=034556//sTemp[1];
Py-Coder
  • 2,024
  • 1
  • 22
  • 28
3

I just wanted to write an algorithm instead of using Java built-in functions:

public static List<String> split(String str, char c){
    List<String> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++){
        if(str.charAt(i) != c){
            sb.append(str.charAt(i));
        }
        else{
            if(sb.length() > 0){
                list.add(sb.toString());
                sb = new StringBuilder();
            }
        }
    }

    if(sb.length() >0){
        list.add(sb.toString());
    }
    return list;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2
String s = "TnGeneral|DOMESTIC";
String a[]=s.split("\\|");
System.out.println(a.toString());
System.out.println(a[0]);
System.out.println(a[1]);

Output:

TnGeneral
DOMESTIC
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

To split a string, uses String.split(regex). Review the following examples:

String data = "004-034556";
String[] output = data.split("-");
System.out.println(output[0]);
System.out.println(output[1]);

Output

004
034556

Note:

This split (regex) takes a regex as an argument. Remember to escape the regex special characters, like period/dot.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KIBOU Hassan
  • 381
  • 4
  • 13
1

You can use the method split:

public class Demo {
    public static void main(String args[]) {
        String str = "004-034556";

        if ((str.contains("-"))) {
            String[] temp = str.split("-");
            for (String part:temp) {
                System.out.println(part);
            }
        }
        else {
            System.out.println(str + " does not contain \"-\".");
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jamith NImantha
  • 1,999
  • 2
  • 20
  • 27
0
String s="004-034556";
for(int i=0;i<s.length();i++)
{
    if(s.charAt(i)=='-')
    {
        System.out.println(s.substring(0,i));
        System.out.println(s.substring(i+1));
    }
}

As mentioned by everyone, split() is the best option which may be used in your case. An alternative method can be using substring().

SAM Jr
  • 32
  • 6
0

To split a string, use String.split(regex):

String phone = "004-034556";
String[] output = phone.split("-");
System.out.println(output[0]);
System.out.println(output[1]);

Output:

004
034556
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KIBOU Hassan
  • 381
  • 4
  • 13
0
 String string = "004^034556-34";
 String[] parts = string.split(Pattern.quote("^"));

If you have a special character then you can use Patter.quote. If you simply have dash (-) then you can shorten the code:

 String string = "004-34";
 String[] parts = string.split("-");

If you try to add other special character in place of dash (^) then the error will generate ArrayIndexOutOfBoundsException. For that you have to use Pattern.quote.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aditya Singh
  • 633
  • 1
  • 5
  • 8
0

I used a string called stringValue and is in the form of something like this "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter".

I will split up the stringValue using the "," as the colon.

And then I would simply like to SetText() of three different TextViews to display that string.

String stringValue = "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter";
String ValueSplitByColon[] = stringValue.split(",");

String firstValue = ValueSplitByColon[0];
String secondValue = ValueSplitByColon[1];
String thirdValue = ValueSplitByColon[2];

txtV1.setText(firstValue);
txtV2.setText(secondValue;
txtV3.setText(thirdValue;

It gives the output as:

  1. The txtV1 value is: Those who had coins

  2. The txtV2 value is: enjoyed in the rain

  3. The txtV3 value is: those who had notes were busy looking for the shelter

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pramesh Bhalala
  • 273
  • 1
  • 3
  • 9
0

If you are validating for alphanumeric then change the regex to [A-Za-z0-9]+-[A-Za-z0-9]+

    public static final Pattern VALIDATE_PATTERN = Pattern.compile("[0-9]+-[0-9]+");

public static String[] validateString(String str) {
    if(VALIDATE_PATTERN.matcher(str).find()) {
        String[] output = str.split("-");
        if(output.length != 2) {
            throw new RuntimeException("Invalid string format");
        }
        return output;
    } else {
        throw new RuntimeException("Invalid string format");
    }
}
0

Splitting and then printing string by using stream

String input = "004-034556";
Stream<String> stream = Arrays.stream(input.split( "-" ));
stream.forEach(System.out::println);
burak isik
  • 395
  • 5
  • 6
0

Using Pattern is Java 8. Below is the way!!

package com.company;

import java.util.regex.Pattern;

public class umeshtest {

    public static void main(String a[]) {
        String ss = "I'm Testing and testing the new feature";
        Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umesh Sulakude
  • 286
  • 2
  • 14
-1

From the documentation:

public String[] split(String regex,int limit) Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Basically you can do something like this:

String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array
   System.out.println(subString);
}

Output:

123
456
789
123
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-1

I looked at all the answers and noticed that all are either 3rd party-licenced or regex-based.

Here is a good dumb implementation I use:

/**
 * Separates a string into pieces using
 * case-sensitive-non-regex-char-separators.
 * <p>
 * &nbsp;&nbsp;<code>separate("12-34", '-') = "12", "34"</code><br>
 * &nbsp;&nbsp;<code>separate("a-b-", '-') = "a", "b", ""</code>
 * <p>
 * When the separator is the first character in the string, the first result is
 * an empty string. When the separator is the last character in the string the
 * last element will be an empty string. One separator after another in the
 * string will create an empty.
 * <p>
 * If no separators are set the source is returned.
 * <p>
 * This method is very fast, but it does not focus on memory-efficiency. The memory
 * consumption is approximately double the size of the string. This method is
 * thread-safe but not synchronized.
 *
 * @param source    The string to split, never <code>null</code>.
 * @param separator The character to use as splitting.
 * @return The mutable array of pieces.
 * @throws NullPointerException When the source or separators are <code>null</code>.
 */
public final static String[] separate(String source, char... separator) throws NullPointerException {
    String[] resultArray = {};
    boolean multiSeparators = separator.length > 1;
    if (!multiSeparators) {
        if (separator.length == 0) {
            return new String[] { source };
        }
    }
    int charIndex = source.length();
    int lastSeparator = source.length();
    while (charIndex-- > -1) {
        if (charIndex < 0 || (multiSeparators ? Arrays.binarySearch(separator, source.charAt(charIndex)) >= 0 : source.charAt(charIndex) == separator[0])) {
            String piece = source.substring(charIndex + 1, lastSeparator);
            lastSeparator = charIndex;
            String[] tmp = new String[resultArray.length + 1];
            System.arraycopy(resultArray, 0, tmp, 1, resultArray.length);
            tmp[0] = piece;
            resultArray = tmp;
        }
    }
    return resultArray;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Grim
  • 1,938
  • 10
  • 56
  • 123