我想在java.lang.String
中获得一个字符索引。因此,例如,我想在'2'
字符串中找到"0123456789"
字符索引(索引将为2)。 String类中有任何方法可用于此,还是一个简单的代码?
感谢您的回答!
答案 0 :(得分:2)
您可以遍历字符串并查找您寻找的字符。
只需使用这样的for循环:
String test = "I want to test something";
for(int i=0;i<test.length;i++) {
char t = test.charAt(i);
// do something with char
}
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29
答案 1 :(得分:1)
index
将为-1。
请注意,此代码只会在此字符串中找到第一个“a”。如果你需要找到一个字符的多个位置,那么在另一个答案中使用解决方案遍历字符串。
String str = "there is a letter";
int index = str.indexOf('a');