2016-11-19 26 views
-2

アンドロイドスタジオの文字列から2つの値を解析したいと思います。 Webからデータ型を変更できないため、Inttを解析する必要があります。ウェブから受け取る文字列は 5 am-10amです。長い文字列から整数を解析する方法

文字列「5 am-10am」からこれらの値、つまり5と10を取得するにはどうすればよいですか。 ありがとうございました。

答えて

0

ので、以下のコードは、あなたが与えられているフォーマットを解析する方法をステップバイステップで示します。私はまた、新たに解析された文字列をintとして使うためのステップを追加したので、それらの演算を実行することができました。お役に立てれば。

 `/*Get the input*/ 
     String input = "5am-10am"; //Get the input 

     /*Separate the first number from the second number*/ 
     String[] values = input.split("-"); //Returns 'values[5am, 10am]' 

     /*Not the best code -- but clearly shows what to do*/ 
     values[0] = values[0].replaceAll("am", ""); 
     values[0] = values[0].replaceAll("pm", ""); 
     values[1] = values[1].replaceAll("am", ""); 
     values[1] = values[1].replaceAll("pm", ""); 

     /*Allows you to now use the string as an integer*/ 
     int value1 = Integer.parseInt(values[0]); 
     int value2 = Integer.parseInt(values[1]); 

     /*To show it works*/ 
     int answer = value1 + value2; 
     System.out.println(answer); //Outputs: '15'` 
+0

良いもの男のおかげで...他の回答も正しいかもしれましたが、私はこのanwerが簡単に見つかり、最初 – rishav

+0

でこれを試してみましたあなたは、いつでもrishavありがとうございました! –

1

この種のフォーマット「Xam-Yam」のみが動作します。ここで

String value="5am-10am"; 
value.replace("am",""); 
value.replace("pm","");//if your string have pm means add this line 
String[] splited = value.split("-"); 


    //splited[0]=5 
    //splited[1]=10 
1

は、あなたが使うべきトリックである: -

String timeValue="5am-10am"; 
String[] timeArray = value.split("-"); 
// timeArray [0] == "5am"; 
// timeArray [1] == "10am"; 

timeArray [0].replace("am",""); 
// timeArray [0] == "5";// what u needed 

timeArray [1].replace("am",""); 
// timeArray [1] == "10"; // what u needed 
0

regexを使用して、他の文字列を削除し、数値データのみを残します。以下のサンプルコード:

public static void main(String args[]) { 
    String sampleStr = "5am-10pm"; 
    String[] strArr = sampleStr.split("-"); // I will split first the two by '-' symbol. 

    for(String strTemp : strArr) { 
     strTemp = strTemp.replaceAll("\\D+",""); // I will use this regex to remove all the string leaving only numbers. 
     int number = Integer.parseInt(strTemp); 
     System.out.println(number); 
    } 

} 

これの利点は、他の文字のすべてが削除され、数字のみが残されますので、あなたは特に「午前」または「午後」を削除する必要はありませんです。

0

私はこの方法がより速くなると思います。正規表現は検証されないので、例えば "30 am-30 pm"のように値を解析すると考えてください。検証が分かれています。

final String[] result = "5am-10pm".replaceAll("(\\d)[pa]m", "$1").split("-"); 
System.out.println(result[0]); // -- 5 
System.out.println(result[1]); // -- 10 
関連する問題