user3671540
user3671540

Reputation: 135

Cut string in android

Hi guys i have a string:

String a = "234 - 456";

I want cut this string and assign the first number in int firstnumber and second number a int secondnumber.

is possible? P.S 123 and 456 are dinamyc number!

The numbers are separated with a " - " Thank you

Upvotes: 0

Views: 4438

Answers (5)

dsum27
dsum27

Reputation: 515

You will want to put validation code in for each step. You want to know the value you have is good.

if(a!=null &&a.Contains(" - ")) {
     String[] separated = CurrentString.split(" - ");
}


separated[0]; // This will contain the first number
separated[1]; //  This will contain the second number

Edit

int valueOne= 0; 
int valueTwo= 0;
try {
    valueOne = Integer.parseInt(strings[0]); // firstNumber becomes 234
    valueTwo = Integer.parseInt(strings[1]); // secondNumber becomes 456
} catch(NumberFormatException e) { 
    System.out.println("Please enter real numbers!");
}

Upvotes: 2

william.eyidi
william.eyidi

Reputation: 2365

To separate your string you should use a StringTokenIzer and make with a "-" as a delimiter and make sure to trim the token you got.

String a = "234 - 456";

        int number_1 = 0, number_2 = 0;

        StringTokenizer stringTokenizer = new StringTokenizer(a, "-");

        if(stringTokenizer.hasMoreTokens()){


            number_1 =  Integer.valueOf(stringTokenizer.nextToken().trim()).intValue();
            number_2 =  Integer.valueOf(stringTokenizer.nextToken().trim()).intValue();

        }

Upvotes: 0

Zach
Zach

Reputation: 4792

You can use str.split(); Example:

String a = "234 - 456";
String[] strings = a.split(" - ");
// Then you can parse them
// You may want to do a check here to see if the user entered real numbers or not
// This is only needed for user input, if the numbers are hard coded you don't need this, although it doesn't hurt to have it
int firstNumber = 0; // Assign them before hand so you can use them after the try catch
int secondNumber = 0;
try {
    firstNumber = Integer.parseInt(strings[0]); // firstNumber becomes 234
    secondNumber = Integer.parseInt(strings[1]); // secondNumber becomes 456
} catch(NumberFormatException e) { 
    System.out.println("Please enter real numbers!");
}

Upvotes: 9

Matúš Bartko
Matúš Bartko

Reputation: 2457

String[] parts = a.split(" - ");
int[] numb = new int[parts.length];
for(int n = 0; n < parts.length; n++) {
   numb[n] = Integer.parseInt(parts[n]);
}
firstnumber = numb[0];
secondnumber = numb[1];

Upvotes: 0

C0L.PAN1C
C0L.PAN1C

Reputation: 12243

Below should work, use split() function:

String[] strArray = input.split(" - ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);
}

int intA = intArray[0];
int intB = intArray[1];

Upvotes: 0

Related Questions