在线工具 在线编程 在线白板 在线工具 在线编程 在线白板

java 如何查找匹配的字符和字符串

我请问一下,java 如何查找匹配的字符和字符串?

输入一段字符 然后输入要查询的字符或字符串 返回出所有这些字符或字符串的位置 我只会查第一个位置咧
最新回答
呸狗屁的爱情っ

2025-03-02 01:16:42

通过indexOf进行查找

示例:

String str = "abcdefg";
if(str.indexOf("cd")>=0){//这里查找str中是否存在"cd"字符串,如果存在则会返回大于等于0的数,如果不存在,则返回-1
   System.out.println("找到了");
}

补充indexOf

1、返回 String 对象内第一次出现子字符串的字符位置。

2、string.indexOf(subString[, startIndex])

1)参数 
string

必选项。String 对象或文字。

subString 必选项。

要在 String 对象中查找的子字符串。

starIndex 可选项。

该整数值指出在 String 对象内开始查找的索引。如果省略,则从字符串的开始处查找。

2)说明 
indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。

客情寄风絮

2025-03-02 01:11:56

import java.io.*;

public class SearchWords {

public static void main(String[] args) throws Exception {
String s = "";
System.out.println("请输入字符串:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();

while (true) {
int num = 0;
System.out.println("请输入要查找的字符串: ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String user_word = br1.readLine().trim();
if (!user_word.equals("exit")) {
System.out.println("您要查找的字符串是:" + user_word);
}
if (user_word.equals("exit")) {// 直到输入的是exit,程序退出。
br1.close();
System.exit(0);
} else {
int line = 0;
int index = 0;
int index1 = 0;
line++;
while ((index1 = s.indexOf(user_word, index)) >= 0) {
num++;
index += index1 + 1;
System.out.println("找到您要的字符串了,在:第" + (index1 + 1) + "个位置");
}
// }
}
if (num == 0) {
System.out.println("Sorry,没找到您要查找的字符串!!!");
}
}
}
}
吶誰咱吢疼

2025-03-02 00:46:38

你可以自己写个方法的!
从返回的第一个位置开始substring,同时记住位置。

public int[] getOffset(String str,String s){
int[] arr=new int[str.length];
int j=1;
while(str.indexOf(s)!=-1){
int i=str.indexOf(s);
if(j==1){
arr[j-1]=i;
}else{
arr[j-1]=i+arr[j-2]+1;
}
String st=str.substring(i+1);
System.out.println(st);
str=st;
j++;
System.out.println("j="+j);
}
return arr;
}

public static void main(String[] args) {

String str="abcaabbddab";
StringText st=new StringText();
int[] i=st.getOffset(str, "ab");
for(int j:i){
System.out.println(j);
}
}
人家有伞,我有大头。

2025-03-02 01:14:36

初学者答案:
用for循环,截取字符串的长度,然后逐个进行比较,如果正确,返回他的位置。
薄荷梦

2025-03-02 00:37:39

String.indexOf(start, subStr);

int index = s.indexOf(subStr);
while(index != -1){
System.out.println(index);
index = s.indexOf(index, subStr);
}