网站首页 > 文章中心 > 其它

找出子串位置java代码

作者:小编 更新时间:2023-08-08 14:36:50 浏览量:13人看过

java统计字符子串在字符串中的位置和次数,急求,要代码的

public static void main(String[] args) {

String str = "asfasfnabaasdfnbassdnbasnbasdnbadfasdfnba";

String key = "nba";

int startindex = 0;

找出子串位置java代码-图1

int count = 0;

while ((startindex = str.indexOf(key, startindex)) = 0) {

count++;

System.out.println("位置:" + startindex);//可以提前声明一个数组用来存放

startindex += key.length();

}

System.out.println("总数" + count);

找出子串位置java代码-图2

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());//如果有,则输出

java中子串的查找,删除,替换

public?class?Strings{

public?static?void?main(String[]?args){

String?str?=?"字符串";

找出子串位置java代码-图3

if(str.indexOf("串")?!=?-1){

System.out.println("包含串子");

}else{

System.out.println("不包含串子");

System.out.println("删除后为:"?+?str.replace("串",""));

System.out.println("替换后为:"?+?str.replace("串","!"));

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();

s1 = new Scanner(System.in).nextLine();

以上就是土嘎嘎小编为大家整理的找出子串位置java代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章