Java 查找字符串中字符的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19314228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find Positions of a Character in a String
提问by Rastin Radvar
How can I find a character in a String
and print the position of character all over the string? For example, I want to find positions of 'o'
in this string : "you are awesome honey"
and get the answer = 1 12 17
.
如何在 a 中找到一个字符String
并在整个字符串中打印字符的位置?例如,我想'o'
在这个字符串中找到位置:"you are awesome honey"
并得到答案 = 1 12 17
。
I wrote this, but it doesn't work :
我写了这个,但它不起作用:
public class Pos {
public static void main(String args[]){
String string = ("You are awesome honey");
for (int i = 0 ; i<string.length() ; i++)
if (string.charAt(i) == 'o')
System.out.println(string.indexOf(i));
}
}
采纳答案by Etienne Miret
You were almost right. The issue is your last line. You should print i
instead of string.indexOf(i)
:
你几乎是对的。问题是你的最后一行。您应该打印i
而不是string.indexOf(i)
:
public class Pos{
public static void main(String args[]){
String string = ("You are awesome honey");
for (int i = 0 ; i<string.length() ; i++)
if (string.charAt(i) == 'o')
System.out.println(i);
}
}
回答by Weyland Yutani
Start from the first character and iterate over all the characters till you reach the end. At each step test whether the character is a 'o'. If it is then print the position.
从第一个字符开始,遍历所有字符直到结束。在每一步测试字符是否是“o”。如果是,则打印位置。
回答by Samuel Petrosyan
static ArrayList<String> getCharPosition(String str, char mychar) {
ArrayList<String> positions = new ArrayList<String>();
if (str.length() == 0)
return null;
for (int i = 0; i < str.length(); i ++) {
if (str.charAt(i) == mychar) {
positions.add(String.valueOf(i));
}
}
return positions;
}
String string = ("You are awesome honey");
ArrayList<String> result = getCharPosition(string, 'o');
for (int i = 0; i < result.size(); i ++) {
System.out.println("char position is: " + result.get(i));
}
Output:
输出:
char position is: 1
char position is: 12
char position is: 17
回答by Lukas Warsitz
Here in Java:
在 Java 中:
String s = "you are awesome honey";
char[] array = s.toCharArray();
for(int i = 0; i < array.length; i++){
if(array[i] == 'o'){
System.out.println(i);
}
}
回答by Phan Van Linh
Here is the function to find all positions of specific character in string
这是查找字符串中特定字符的所有位置的函数
public ArrayList<Integer> findPositions(String string, char character) {
ArrayList<Integer> positions = new ArrayList<>();
for (int i = 0; i < string.length(); i++){
if (string.charAt(i) == character) {
positions.add(i);
}
}
return positions;
}
And use it by
并使用它
ArrayList<Integer> result = findPositions("You are awesome honey",'o');
// result will contains 1,12,17