java中要获取字符在字符串中的位置,可以通过indexof()函数来实现。
(推荐教程:java入门程序)
函数语法:
indexof() 函数有以下四种形式:
public int indexof(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexof(int ch, int fromindex): 返回从 fromindex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexof(string str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexof(string str, int fromindex): 返回从 fromindex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
参数介绍:
ch -- 字符,unicode 编码。
fromindex -- 开始搜索的索引位置,第一个字符是 0 ,第二个是 1 ,以此类推。
str -- 要搜索的子字符串。
(视频教程推荐:java视频教程)
代码实现:
public class main { public static void main(string args[]) { string string = "aaa456ac"; //查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1. system.out.println(string.indexof("b")); // indexof(string str); 返回结果:-1,"b"不存在 // 从第四个字符位置开始往后继续查找,包含当前位置 system.out.println(string.indexof("a",3));//indexof(string str, int fromindex); 返回结果:6 //(与之前的差别:上面的参数是 string 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99 // 从头开始查找是否存在指定的字符 system.out.println(string.indexof(99));//indexof(int ch);返回结果:7 system.out.println(string.indexof('c'));//indexof(int ch);返回结果:7 //从fromindex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。 system.out.println(string.indexof(97,3));//indexof(int ch, int fromindex); 返回结果:6 system.out.println(string.indexof('a',3));//indexof(int ch, int fromindex); 返回结果:6 }}
输出结果:
-167766
以上就是java如何获取字符在字符串中的位置的详细内容。