Home > Java > javaTutorial > What is the use of indexof method in java

What is the use of indexof method in java

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-05-17 14:28:06
forward
1814 people have browsed it

indexof method:

Note: The indexOf method returns an integer value indicating the starting position of the substring within the String object. If the substring is not found, -1 is returned.

public class IndexOf{
	public static void main(String[] args){
		String s="李宏#王海#林巧#陆寻#唐梅";
		String q="#"; //需要查找的字符串
		String err="*"; //不存在的字符串
		int i=0;
		for(int j=0;j<s.length();j++){ //循环所有字符串
			String get=s.substring(j,j+1); //打印所有字符串
			if(get.equals(q)){ //判断#字是否出现
				i++; //#字出现次数
			}
		}
		System.out.println("总共有"+s.length()+"个字符串");
		System.out.println("#字共出现了"+i+"次"); //#字符总共出现的次数
		System.out.println("第一个#字出现在字符串的"+s.indexOf(q)+"个位置"); 
		if(s.indexOf(err)==-1){ //返回-1则表示字符不存在字符串中
			System.out.println("*字在字符串中不存在");
		}
	}
}
Copy after login

Run results:

There are 14 strings in total.
# words appear 4 times in total.
The first # word appears in 2 of the strings. The word at position
* does not exist in the string

The above is the detailed content of What is the use of indexof method in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template