我有一个字符串(“恐龙”)的位置,我不知道到底怎么样,但我如何得到字符“O”的位置,并为它所有可能得到两个职位,就像我的字符串是(“池”)我如何找到一个字符
回答
至于你的第一个问题,你可以使用String#indexOf(int)获得你的字符串中的每个'o'的索引。
int oPos = yourString.indexOf('o');
关于你的第二个问题,有可能通过使它使用String.indexOf(int, int)的方法,跟踪上一个索引,让你不重复搜索的字符串的一部分,以获得特定字符的所有位置。您可以将位置存储在数组或列表中。
使用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”以及
你说得对,这是非常过分 – HXCaine
一H,是的,但它也是非常,非常灵活;) – MadProgrammer
我不介意人们偶尔会走极端,但拼写错误“嘿”是不可饶恕的:-) – paxdiablo
您是否尝试将字符串转换为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));
}
- 1. 如何找到一个字符串
- 2. MYSQL如何找到一个字符串
- 3. 如何找到一个字符不同
- 4. Python:我如何找到一个字符串中的每个字符的列表?
- 5. 如何遍历一个字符串并找到某个字符?
- 6. PHP字符串如何找到一串数字一个数字
- 7. 如何找到一个字符串中的字符串
- 8. 如何找到在C中第一个字符的字符串++
- 9. Scheme:如何找到一个字符串中的字符位置
- 10. 如何找到一个字符串的大写字符串?
- 11. 如何找到一个字符串,直到找到一个选定的字符串?
- 12. 如何在一个DataTable的列中找到一个字符串
- 13. 我如何能在一个字符串找到字母数字的
- 14. 如何找到一个字符中的一个字符C语言
- 15. 如何找到一个字符的位置在一个字符串中PHP
- 16. 如何找到一个字符串是否包含在另一个字符串
- 17. 如何找到一个字符串出现在另一个字符串
- 18. C++:查找字符串中的一个字符,然后找到另一个字符前一个字符
- 19. 如何拆分一个字符串并在另一个字符串中找到一个字符串?
- 20. 找到一个非数字字符
- 21. 我将如何找到一个局部字匹配/查找C++
- 22. 找到一个字符串,但返回前一个字符串
- 23. 如何在Python中的字符串中找到一个数字?
- 24. Python:如何找到字符串的第一个字母?
- 25. 如何找到两个字符串
- 26. 我想知道如何在一个字符串中找到一个特殊字符
- 27. 如何在另一个字符串中找到字符串的一部分?
- 28. 如何在两个子串之间找到一个字符串?
- 29. 我如何添加一个int到一个字符串
- 30. 我如何调用一个字符串方法到一个JPanel
我只发现代码的字符串替换一个字符,现在我想用这个代码,但我可以“T的使用,如果我不能找到的位置char –
[documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)是你的朋友,你正在寻找的方法是'indexOf'。 – Jeffrey