简体   繁体   English

从字符串中删除设置的子字符串

[英]Deleting the set substring from string

I need to delete the set substring from string in Java. 我需要从Java中的字符串中删除设置的子字符串。 How I can to do it? 我该怎么做? example: 例:

string st1="The end of the text"; string st2="end of the ";

result: 结果:
st1="The text".

You can do this: 你可以这样做:

String newString = st1.replace(st2, "");

// String newString2 = st1.replaceAll(st2, ""); Alternative
// String newString3 = st1.replaceFirst(st2, ""); Alternative 2

However, your question smell homework so you should add that tag on future questions if this is true. 但是,您的问题闻起来有点作业,因此,如果是这样,您应该在以后的问题上添加该标签。

Java String documentation Java String文档

以下是您想要的吗?

str1 = st1.replace(st2,"");

If you want to use substring() , you can do it like this: 如果要使用substring() ,可以这样进行:

public static String getCustomString(String s1, String s2)
{
    if(s1.length() >= s2.length())
    {
        if(s1.contains(s2))
            return s1.substring(0, s1.indexOf(s2)) + s1.substring(s1.indexOf(s2) + s2.length());
    }
    else
    {
        if(s2.contains(s1))
            return s2.substring(0, s2.indexOf(s1)) + s2.substring(s2.indexOf(s1) + s1.length());
    }
    return "";
}

If homework (with minimal usage of Java API calls: 如果进行家庭作业(使用最少的Java API调用):

public void subString(String st1, String st2) {

   int s2len = st2.length();
   int s1len = st1.length();

   int i = 0;
   int count = 0;
   while(i <= st1.length() && i+st2.length() <= st1.length()) {

       if (st1.substring(i, i+st2.length()).equalsIgnoreCase(st2)) {
          st1 = (i > 0? st1.substring(0, i) : "") + st1.substring(i+st2.length());
          i=0;
       }
       else {
          i++;
       }
   }
   System.out.println(st1);
}

Otherwise: 除此以外:

st1.replace(st2, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM