Java String indexOf() 函数的完整指南

252 阅读2分钟

一个常见的情况是,系统管理员想找到客户的电子邮件ID中'@'字符的索引,然后想获得剩余的子串。在这种情况下,可以使用indexOf()方法。

Java字符串 indexOf()

Java 字符串indexOf()是一个内置的方法,用于返回一个给定的字符值或子串的索引。如果没有找到,那么它返回-1。索引计数器从0开始。indexOf()方法用于根据indexOf()方法的参数中指定的标准,获得String类型对象的特定索引的整数值。

indexOf方法的类型

String indexOf( char ch):

indexOf(char ch)方法返回给定字符第一次出现的索引;如果该字符不存在,则返回-1。

语法

stringName.indexOf(character)

这里stringName 是你想从中找到字符的索引的字符串,character 是指你想找到其索引的那个字符。

请看下面的程序:

class IndexOfStr {
	public static void main(String args[]) {
		String str = "Welcome to Appdividend";
		System.out.print("First occurence of 'd' in the string is: ");
		// we are finding the index of 'd'
		// it will return the index of first
		// occurence of 'd'
		System.out.println(str.indexOf('d'));

	}
}

请看输出结果:

Java indexOf() Function

String indexOf(char ch, int x)

indexOf()方法返回一个字符串中存在的给定字符的索引,但它在索引x处搜索其位置 。如果它不能找到该字符的索引,则返回-1。

语法

int indexOf(int ch, int start)

这里ch是我们想找到的字符的位置,start是我们想找到ch的索引的起始点。

请看下面的代码:

class IndexOfStr {
	public static void main(String args[]) {
		String str = "Welcome to Appdividend";
		System.out.print("First occurence of 'd' after index 15 is: ");
		// we are finding the index of 'd'
		// it will return the index of d
		// after index position 15
		System.out.println(str.indexOf('d', 15));

	}
}

请看输出结果:

Java String indexOf() Example

String indexOf(String str)

indexOf(String str)方法返回一个给定字符串中子串第一次出现的索引。

语法

int indexOf(String str)

这里str是子串,我们想从给定的字符串中找到其索引:

class IndexOfStr {
	public static void main(String args[]) {
		String str = "I like Apple. What do you like?";
		System.out.print("First occurence of 'like' in the string is: ");
		// Initialising search string
		String substr = new String("like");
		// we are finding the index of 'like'
		// it will return the index of first
		// occurence of 'like'
		System.out.println(str.indexOf(substr));

	}
}

请看输出结果:

indexof3

String indexOf(String str, int x)

indexOf()方法返回给定子串的索引,但是从给定索引x开始。在索引位置 x之后 ,它 将返回给定子串的第一次出现。

语法

int indexOf(String str, int x)

这里 str 是我们想找到的字符的位置, x 是 我们想找到 str的索引开始的位置 。

请看程序:

class IndexOfStr {
	public static void main(String args[]) {
		String str = "I like Apple. What do you like?";
		System.out.print("First occurence of 'like' after index 7 is: ");
		// Initialising search string
		String substr = new String("like");
		// we are finding the index of 'like'
		// it will return the index of first
		// occurence of 'like'
		System.out.println(str.indexOf(substr, 7));

	}
}

看输出。

indexof4

本教程到此结束。