【发布时间】:2012-08-27 13:53:35
【问题描述】:
我有一个字符串(“Dinosaur”),但我不知道如何获取字符“o”的位置,是否有可能获得两个位置,例如我的字符串是(“游泳池”)
【问题讨论】:
-
我只找到了替换字符串中字符的代码,现在我想使用此代码,但如果找不到字符的位置,我将无法使用
-
documentation 是您的朋友。你要找的方法是
indexOf。
我有一个字符串(“Dinosaur”),但我不知道如何获取字符“o”的位置,是否有可能获得两个位置,例如我的字符串是(“游泳池”)
【问题讨论】:
indexOf。
对于第一个问题,您可以使用String#indexOf(int) 获取字符串中每个“o”的索引。
int oPos = yourString.indexOf('o');
至于您的第二个问题,可以通过使用String.indexOf(int, int) 的方法获取给定字符的所有位置,跟踪前一个索引,这样您就不会重复搜索字符串的部分。您可以将位置存储在数组或列表中。
【讨论】:
KeyEvent.VK_O == 79 == 'O'(大写 O)。只需使用小写字符文字'o'。
在循环中使用indexOf:
String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
System.out.println(idx);
idx = s.indexOf('o', idx + 1);
}
【讨论】:
简单地说:
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;
}
【讨论】:
这可能有点过火了,但是嘿;)
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”
【讨论】:
您是否尝试过将 String 转换为 char 数组?
int counter = 0;
String input = "Pool";
for(char ch : input.toCharArray()) {
if(ch == 'o') {
System.out.println(counter);
}
counter += 1;
}
【讨论】:
试试这个
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));
}
【讨论】: