2014-10-30 4 views
2

나는 지금은 문자열에서 정수를 분리하는 방법은 무엇입니까?

if (exp.contains("to")) 
{ 
    // here I want to fetch the integers 7 and 10 
} 

방법 ( Integer로서 구문 분석) 문자열 7 to 10에서 7과 10를 분리 할 수있는 상태를 유지하고 문자열을

String exp = "7 to 10"; 

있습니다.

구분 기호를 사용하면 분명히 할 수 있지만 이렇게하는 방법을 알고 싶습니까?

+0

이 문자열이'spaces'이 포함되어 있습니까? '7 10'은 정수가 아닌 문자열 내부의 값입니다 –

+0

'String.split()'을 사용하고 싶지 않다는 뜻입니까? – Tariq

+0

예 공간은 문자열이 "7 to 10"입니다. @SanKrish – suganya

답변

1

코드는,

import java.io.*; 

public class test 
{ 
    public static void main(String[] args) { 

     String input="7 to 10";//pass any input here that contains delimeter "to" 
     String[] ans=input.split("to"); 

     for(String result:ans) { 
     System.out.println(result.trim()); 
     } 
    } 
} 

확인하고 당신을 위해 잘 작동하는지 알려 주시기 바랍니다.

+0

thnx..it worked :) – suganya

8

사용하여 분할 :

if (exp.contains(" to ")) { 
     String[] numbers = exp.split(" to "); 
     // convert string to numbers 
    } 

사용 정규식 : 여기

Matcher mat = Pattern.compile("(\\d+) to (\\d+)").matcher(exp); 
    if (mat.find()) { 
     String first = mat.group(1); 
     String second = mat.group(2); 
     // convert string to numbers 
    } 
+0

또는 심지어 if (exp.contains ("to") " – Bohemian

+0

또는'if (exp.matches ("(\\ d +) ~ to ")"또는 " (\\ d +) ")) {String [] res = exp.split ("to ")}':) – Willmore

1

다음 코드를 시도하면 모든 문자열에서 작동합니다.

String test="7 to 10"; 
String tok[]=test.split(" (\\w+) "); 
for(String i:tok){ 
    System.out.println(i); 
} 

출력 :

7 
10 
관련 문제