2012-08-26 4 views
0

나는 String ("Dinosaur")을 가지고 있는데 정확히 어떻게 모르겠지만 char "o"의 위치를 ​​얻는 방법은 무엇입니까? 내 문자열 ("풀")처럼 두 위치를 얻을 수있는 모든숯의 위치를 ​​알아내는 방법

+0

가, 지금은이 코드를 사용하려는 시도하지만 난 "t의 사용은 난의 위치를 ​​찾을 수 없습니다 수있는 경우 char –

+1

[documentation] (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)은 친구입니다. 찾고있는 방법은'indexOf'입니다. – Jeffrey

답변

3

첫 번째 질문은 String#indexOf(int)을 사용하여 문자열의 모든 'o'색인을 가져올 수 있습니다. 두 번째 질문에 대해서는

int oPos = yourString.indexOf('o'); 

, String.indexOf(int, int)를 사용하는 방법을 당신이 문자열의 일부를 검색을 반복하지 않도록 이전 인덱스를 추적하여 해당 문자의 모든 위치를 얻을 수 있습니다. 배열이나리스트에 위치를 저장할 수 있습니다. 루프와

+0

' KeyEvent.VK_O == 79 == 'O'(대문자 O). 소문자 문자 "O"를 사용하십시오. – Jeffrey

+0

Derp; 고쳐졌습니다. – Vulcan

1

사용 indexOf : 간단하게

String s = "Pool"; 
int idx = s.indexOf('o'); 
while (idx > -1) { 
    System.out.println(idx); 
    idx = s.indexOf('o', idx + 1); 
} 
0

:

public static int[] getPositions(String word, char letter) 
{ 
    List<Integer> positions = new ArrayList<Integer>(); 
    for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i); 

    int[] result = new int[positions.size()]; 
    for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i); 

    return result; 
} 
0

이 아마 헤이 보드 위에 조금가는 있지만)

String master = "Pool"; 
String find = "o"; 

Pattern pattern = Pattern.compile(find); 
Matcher matcher = pattern.matcher(master); 

String match = null; 

List<Integer[]> lstMatches = new ArrayList<Integer[]>(5); 
while (matcher.find()) { 

    int startIndex = matcher.start(); 
    int endIndex = matcher.end(); 

    lstMatches.add(new Integer[] {startIndex, endIndex}); 

} 

for (Integer[] indicies : lstMatches) { 

    System.out.println("Found " + find + " @ " + indicies[0]); 

} 

나에게

를 제공합니다
Found o @ 1 
Found o @ 2 

좋은 점은 "oo"도 찾을 수 있다는 것입니다.

+0

맞습니다. 이것은 매우 외판입니다. – HXCaine

+0

A 예, 그렇지만 매우 유연합니다.) – MadProgrammer

+0

사람들은 가끔 배 밖으로 빠져들지 만, "헤이"는 용서할 수 없습니다 :-) – paxdiablo

0

String을 char 배열로 변환 해 보았습니까?

int counter = 0; 
String input = "Pool"; 
for(char ch : input.toCharArray()) { 
    if(ch == 'o') { 
     System.out.println(counter); 
    } 
    counter += 1; 
} 
0

문자열의 문자를 대체 난 단지 코드가 발견 한이

String s= "aloooha"; 
char array[] = s.toCharArray(); 
Stack stack = new Stack(); 

for (int i = 0; i < array.length; i++) { 
    if(array[i] == 'o'){ 
     stack.push(i); 
    } 
}   
for (int i = 0; i < stack.size(); i++) { 
    System.out.println(stack.get(i)); 
} 
관련 문제