简体   繁体   English

涉及 StringBuilder 的 Java replaceSubstring() 方法?

[英]Java replaceSubstring() method that involves StringBuilder?

A part of my assignment is to create a method that replaces all the occurences of string 2 that occur in string 1 with string 3. So if the sentence was : "the dog jumped over the fence", I'd want the method to replace all occurrences of whatever string 2 is which let's say is "the" with the content of string 3 which let's say is "that".我的任务的一部分是创建一个方法,用字符串 3 替换字符串 1 中出现的字符串 2 的所有出现。所以如果句子是:“狗跳过栅栏”,我希望该方法替换所有出现的字符串 2 是“the”,字符串 3 的内容是“that”。

So I'd want it to say "that dog jumped over that fence".所以我希望它说“那条狗跳过了那个栅栏”。

This is really easy if my teacher professor allowed for a more convenient way, but this entire course is just inconvenient when it comes to learning, so I HAVE to use a StringBuilder object.如果我的老师教授允许使用更方便的方法,这真的很容易,但是整个课程在学习方面很不方便,所以我必须使用 StringBuilder 对象。

So far my code for replaceSubstring() is到目前为止,我的 replaceSubstring() 代码是

   public static String replaceSubstring(String str1, String str2, String str3)
   {
      String str1Copy = str1, str2Copy = str2, str3Copy = str3;

      if (str2Copy.equals(str3Copy))
      {
         return str1Copy;
      }

      StringBuilder b = new StringBuilder(str1Copy);

      int index = b.indexOf(str2Copy);

      b.replace(index, (index + str2Copy.length()), str3Copy);

      index = b.indexOf(str3Copy);


      return b.toString();
   }

However I'm running into an issue, because when I run this code in an application class that prints out the return statement of this method, I get但是我遇到了一个问题,因为当我在打印出此方法的返回语句的应用程序类中运行此代码时,我得到

After replacing "the" with "that", the string: that dog jumped over the fence

In my console.在我的控制台中。 The original string is "the dog jumped over the fence", and my code should change it to "that dog jumped over that fence", however it just changes the first occurrence of "the" and not the second one.原始字符串是“狗跳过栅栏”,我的代码应该将其更改为“那只狗跳过了栅栏”,但是它只更改了第一次出现的“the”而不是第二次。 I'm really scratching my head over this because I understand how I could just do something like我真的为此挠头,因为我明白我怎么能做这样的事情

return string1.replaceAll(string2, string3);

And call it a day, but I'd lose points for not doing it how my professor wants it which is by using a StringBuilder object.并称它为一天,但我会因为没有按照我的教授希望的方式使用 StringBuilder 对象而失去积分。 What am I missing here?我在这里缺少什么? Also, I can't import any packages created by someone else.另外,我无法导入其他人创建的任何包。 I HAVE to use the generic and basic java kit.我必须使用通用和基本的 java 工具包。

EDIT: New code that seems to work编辑:似乎有效的新代码

   public static String replaceSubstring(String str1, String str2, String str3)
   {
      String str1Copy = new String (str1), str2Copy = new String (str2), str3Copy = new String (str3);

      if (str2Copy.equals(str3Copy))
      {
         return str1Copy;
      }

      StringBuilder b = new StringBuilder(str1Copy);

      int index = b.indexOf(str2Copy);
      while (index != -1)
      {
         b.replace(index, (index + str2Copy.length()), str3Copy);
         index = b.indexOf(str2Copy, index + 1);
      }

      return b.toString();
   }

You need to loop while there are no more occurrences of str2 in str1 .您需要在str1中不再出现str2进行循环。 indexOf() returns -1 if there are no more occurrences so you can use this to solve this problem.如果不再出现indexOf()返回 -1,因此您可以使用它来解决此问题。 Inside the loop you use the overload indexOf(String str, int fromIndex) .在循环内,您使用重载indexOf(String str, int fromIndex) Also you do not need the copies of the String 's:您也不需要String的副本:

public static String replaceSubstring(String str1, String str2, String str3)
{ 
    if (str2.equals(str3))
    {
        return str1;
    }

    StringBuilder b = new StringBuilder(str1);
    int index = b.indexOf(str2); 
    //Loop while there is still an occurrence of str2       
    while(index != -1) {
        b.replace(index, (index + str2.length()), str3);
        index = b.indexOf(str2, index+str3.length());
    }

    return b.toString();
}

The line:线路:

index = b.indexOf(str2, index+str3.length());

Moves the search to past where we've already found an occurrence.将搜索移动到我们已经找到一个事件的位置。 On the first iteration we just call indexOf() without specifying the starting index, so it will start at the beginning of the String :在第一次迭代中,我们只调用indexOf()而不指定起始索引,因此它将从String的开头开始:

the dog jumped over the fence
^index points to the first occurrence of the (0)

Once we call indexOf() specifying the starting index as index + str3.length() , the starting index will be 0 + 4 so it will move the search to:一旦我们调用indexOf()将起始索引指定为index + str3.length() ,起始索引将为0 + 4因此它将搜索移动到:

that dog jumped over the fence
    ^Start the search here.

To see why this is important if we replace the with tthe , without specifying the starting index it will look like this:要了解如果我们将 替换the tthe重要性,而不指定起始索引,它将如下所示:

the dog jumped over the fence
^found first occurrence. Replace with tthe

Second iteration of loop:循环的第二次迭代:

tthe dog jumped over the fence
 ^Found another one! replace again.

Third iteration of loop:循环的第三次迭代:

ttthe dog jumped over the fence
  ^Another occurrence of the. 

Etc, etc.等等等等。

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

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