如何在字符串中获取字符索引

时间:2016-04-06 17:11:09

标签: java string

我想在java.lang.String中获得一个字符索引。因此,例如,我想在'2'字符串中找到"0123456789"字符索引(索引将为2)。 String类中有任何方法可用于此,还是一个简单的代码?

感谢您的回答!

2 个答案:

答案 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)

如果'a'不在此字符串中,

index将为-1。

请注意,此代码只会在此字符串中找到第一个“a”。如果你需要找到一个字符的多个位置,那么在另一个答案中使用解决方案遍历字符串。

String str = "there is a letter";

int index = str.indexOf('a');