Java源字符串中删除指定字符串,使得最终结果不包含子字符串,记录删除次数?

源字符串例如:123java123jajajavavava123java
要删除的字符串:java
最终结果123123123 count=5.
请问这是怎么实现的啊???

8个回答

String s1 = "123java123jajajavavava123java";
String s2 = "java";
String result = s1;
while(result.contains(s2)){
result = result.replace(s2,"");
System.out.println(result);

    }
    int count = (s1.length() - result.length()) / s2.length();
    System.out.println(count);

  String s1 = "123java123jajajavavava123java";
        String s2 = "java";
        String result = s1;
        while(result.contains(s2)){
            result = result.replace(s2,"");
            System.out.println(result);

        }
        int count = (s1.length() - result.length()) / s2.length();
        System.out.println(count);
qq_21297489
淡然自若 简单直接.很暴力,哈哈,TKS
2 年多之前 回复

/**
* 从源字符串中移除所有目标字符串
* @param targetString 移除目标字符串
* @param sourceString 源字符串
* @return 移除后的源字符串
*/
public static String removeTargetStringFromSourceString(String targetString,String sourceString){
String returnString = "";
if (sourceString.indexOf(targetString) != -1){
String result = sourceString.substring(0, sourceString.indexOf(targetString))
+ sourceString.substring(sourceString.indexOf(targetString)+targetString.length(),sourceString.length());
returnString = removeTargetStringFromSourceString(targetString, result);
} else {
returnString = sourceString;
}
return returnString;
}


次数的话看这个函数执行多少次就行了

qq_21297489
淡然自若 这个递归玩的好 :p,谢谢啦
2 年多之前 回复
 /**
     * 从源字符串中移除所有目标字符串
     * @param targetString  移除目标字符串
     * @param sourceString  源字符串
     * @return  移除后的源字符串
     */
    public static String removeTargetStringFromSourceString(String targetString,String sourceString){
        String returnString = "";
        if (sourceString.indexOf(targetString) != -1){
            String result = sourceString.substring(0, sourceString.indexOf(targetString))
                          + sourceString.substring(sourceString.indexOf(targetString)+targetString.length(),sourceString.length());
            returnString = removeTargetStringFromSourceString(targetString, result);
        } else {
            returnString = sourceString;
        }
        return returnString;
    }

次数的话看这个函数执行多少次就行了

过滤器 过滤字符串 加循环 循环加次数

只能用循环遍历 来删除 遍历你想象的删除工程即可

源字符串是jjavaava
要删除的字符串是java
那删除完后是否是空串?

qq_21297489
淡然自若 空就空呗
2 年多之前 回复

String s1 = "123java123jajajavavava123java";
String s2 = "java";
String result = s1.Replace(s2);
int count = (s1.length() - result.length()) / s2.length();

qq_21297489
淡然自若 你想的很好,但是String类没有你这个repalce的用法,但是谢谢你
2 年多之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 replace应为小写。手工打的,思路很简单。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐