user3270422
user3270422

Reputation: 19

Splitting a string through other ways

I have a string, "004-034556", that I want to split into two strings:

string1 = "004"
string2 = "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. If not, I will throw an exception. How can I do this?

Now one way to achieve this is ...

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]);
}

Upvotes: 0

Views: 157

Answers (4)

AJ.
AJ.

Reputation: 4534

You can do it this way:

String str  = "004-034556";

if (str.contains("-")) { // Check if str contains "-"
    String strSplit[] = str.split("-");
}
else {
    // Throw exception
}

strSplit[0]==> 004

strSplit[1] ==> 034556

Upvotes: 2

IronBlossom
IronBlossom

Reputation: 3917

public class SplitException extends Exception{
    ...
    ...
}

public String[] customSplit(String str, String splitter) {

    String[] splitted = str.split(splitter);
    if (splitted.size() == 0)
        throw new SplitException();
    return splitted;
}

try {
    customSplit("004-034556", "-");
}
catch(SplitException se) {
    se.printStackTrace();
}

Upvotes: 0

Aditya Peshave
Aditya Peshave

Reputation: 667

String[] array = givenString.split("-");

and to check it,

if(givenString.contains("-")) return true;

Upvotes: 0

wlk
wlk

Reputation: 5785

Try this:

String[] spilited = abc.split("-");
if(spilited.size() == 0){
    throw new RuntimeException("String doesn't contain '-');
}

Upvotes: 1

Related Questions