在android中剪切字符串

时间:2014-07-25 15:53:45

标签: java android

大家好我有一个字符串:

String a = "234 - 456";

我想剪切此字符串并在int firstnumber中分配第一个数字,在第二个数字中分配第二个数字。

可能吗? P.S 123和456是dinamyc数字!

数字用"分隔。 - " 谢谢

5 个答案:

答案 0 :(得分:9)

您可以使用str.split();示例:

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!");
}

答案 1 :(得分:1)

您需要为每个步骤添加验证码。你想知道你的价值是好的。

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

修改

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!");
}

答案 2 :(得分:0)

下面应该可以使用split()函数:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

要分隔字符串,您应该使用StringTokenIzer并使用&#34; - &#34;作为分隔符,并确保修剪你得到的令牌。

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();

        }