tags:

views:

169

answers:

5

i have a string 004-034556. now i want to split in into two string.

string1=004
string2=034556

that means the first string will contain characters before '-' and second string will contain characters after '-'. how to do it? i also want to check if the string has '-' in it. if not i will declare an exception. how to do?

+3  A: 

Just use the appropriate method: String#split().

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

To test beforehand if the string contains a -, just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}
BalusC
+2  A: 
String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");

This will split your string into 2 parts. The first element in the array will be the part containing the stuff before the -, and the 2nd 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.

http://download-llnw.oracle.com/javase/6/docs/api/java/lang/String.html

jjnguy
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
+1  A: 
String[] out = string.split("-");

should do thing you want. String class has many method to operate with string.

secmask
"String class has many method to operate with string." Yes, one might say it should.
Tom
A: 

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.

Michael Konietzka
+1  A: 

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(0) +
                               ", second part is " + m.group(1) + ".");
        } 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