
正文
找出子串位置java代码,java查找子串出现的位置
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
java统计字符子串在字符串中的位置和次数,急求,要代码的
public static void main(String[] args) {
String str = "asfasfnabaasdfnbassdnbasnbasdnbadfasdfnba";
String key = "nba";
int startindex = 0;
int count = 0;
while ((startindex = str.indexOf(key, startindex)) = 0) {
count++;
System.out.println("位置:" + startindex);//可以提前声明一个数组用来存放
startindex += key.length();
}
System.out.println("总数" + count);
}
相关问答
Q1: JAVA中怎样在一个字符串中查找给定的子字符串
可以用正则表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class DemoAsm{
public static void main(String[] args){
String str="abcdef";//输入字符串
String reg="cde";//需要查找的字符串
Pattern pattern =Pattern.compile(reg);
Matcher mather=pattern.matcher(str);
while(mather.find()){
System.out.println(mather.group());//如果有,则输出
}
}
}
Q2: java中子串的查找,删除,替换
public class Strings{
public static void main(String[] args){
String str = "字符串";
if(str.indexOf("串") != -1){
System.out.println("包含串子");
}else{
System.out.println("不包含串子");
}
System.out.println("删除后为:" + str.replace("串",""));
System.out.println("替换后为:" + str.replace("串","!"));
}
}
Q3: java循环查找子串出现的所有位置
String s = new Scanner(System.in).nextLine();
System.out.println("输入查找的字符:");
String s1 = new Scanner(System.in).nextLine();
这里s,s1是局部变量啊
改成
s = new Scanner(System.in).nextLine();
System.out.println("输入查找的字符:");
s1 = new Scanner(System.in).nextLine();






