728x90

특정 문자열을 파싱처리하는 걸 처리하는데 동일한 값이 두번 나온다고 한다.

그래서 두번째 값을 읽어낸다고 한다.

한번만 해당 정보가 출력되는 줄 알았는데 동일한 정보가 여러개 있을 수 있는 환경이다.


String gw_alloc;

private void parseDeviceIPAddress(String msg){
    String[] line = msg.split("\\n"); // 라인 단위로 메시지를 분리하라.
    for(int i=0; i < line.length;i++){
        if(line[i].contains("GW=")){  // GW address 추출
            String str = line[i].trim(); // 문자열 앞의 공백 제거 목적
            int stlocation = str.indexOf("GW=");
            int endlocation = str.length();
            String temp = str.substring(stlocation+3, endlocation-1).trim();
            int firstcomma = temp.indexOf(","); // 처음 나오는 , 를 찾아라.
            String gwaddress = temp.substring(0,firstcomma).trim();
            if(gwaddress.length() > 8){
                gw_alloc = gwaddress;
            }
        }
    }
}


그래서 첫번째 값을 읽어내도록 하는 걸 처리하기 위해서 코드를 아래와 같이 ArrayList를 이용해서 수정했다.

ArrayList<String> gw_alloc = new ArrayList<>();

private void parseDeviceIPAddress(String msg){
    String[] line = msg.split("\\n"); // 라인 단위로 메시지를 분리하라.
    for(int i=0; i < line.length;i++){
        if(line[i].contains("GW=")){  // GW address 추출
            String str = line[i].trim(); // 문자열 앞의 공백 제거 목적
            int stlocation = str.indexOf("GW=");
            int endlocation = str.length();
            String temp = str.substring(stlocation+3, endlocation).trim();
            int firstcomma = temp.indexOf(","); // 처음 나오는 , 를 찾아라.
            String gwaddress = temp.substring(0,firstcomma).trim();
            if(gwaddress.length() > 8){
                gw_alloc.add(gwaddress);
            }
        }
    }
}


해당 정보가 있으면 ArrayList 에 add하고 출력할 때는 gw_alloc.get(0); 를 해주면 첫번째 값을 활용할 수 있다.

블로그 이미지

Link2Me

,