2013-05-16 5 views
0

(android 쉘을 통해) 핑 요청을 수행하는 안드로이드 응용 프로그램에서 작업 중이며 콘솔에 표시된 메시지를 읽었습니다. 일반적인 메시지는 다음과 같습니다.핑 메시지의 값을 추출하십시오.

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 
64 bytes from 8.8.8.8: icmp_seq=1 ttl=46 time=186 ms 
64 bytes from 8.8.8.8: icmp_seq=2 ttl=46 time=209 ms 

--- 8.8.8.8 ping statistics --- 
2 packets transmitted, 2 received, 0% packet loss, time 1000ms 
rtt min/avg/max/mdev = 186.127/197.891/209.656/11.772 ms 

위의 메시지를 String에 저장합니다. 시간의 값, 예를 들어 186과 209와 손실에 대한 백분율 (이 경우)을 추출하고 싶습니다.

문자열을 살펴보고 "time ="다음에 값을 살펴볼 생각이었습니다. 그러나 나는 그것을 어떻게하는지 모른다. 값을 추출하기 위해 내가 가지고있는 문자열을 어떻게 조작 할 수 있습니까? 문자열의 각 행을 얻어서

답변

1

시작 : 다음

String[] lines = pingResult.split("\n"); 

, 루프 및 사용 문자열입니다. 당신이 int에 구문 분석하려면

for (String line : lines) { 
    if (!line.contains("time=")) continue; 
    // Find the index of "time=" 
    int index = line.indexOf("time="); 

    String time = line.substring(index + "time=".length()); 
    // do what you will 
} 

, 당신은 추가 할 수 :

int millis = Integer.parseInt(time.replaceAll("[^0-9]", "")); 

이 모든 숫자가 아닌 문자를 제거합니다

당신은 비율이 비슷한 뭔가를 할 수

:

for (String line : lines) { 
    if (!line.contains("%")) continue; 

    // Find the index of "received, " 
    int index1 = line.indexOf("received, "); 

    // Find the index of "%" 
    int index2 = line.indexOf("%"); 

    String percent = line.substring(index1 + "received, ".length(), index2); 
    // do what you will 
} 
+0

완벽 !!!!! 정말 고마워!!!! –

관련 문제