2012-08-26 15 views
0

我有一个字符串(“恐龙”)的位置,我不知道到底怎么样,但我如何得到字符“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

一H,是的,但它也是非常,非常灵活;) – MadProgrammer

+0

我不介意人们偶尔会走极端,但拼写错误“嘿”是不可饶恕的:-) – paxdiablo

0

您是否尝试将字符串转换为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)); 
} 
相关问题