简体   繁体   English

Java中如何替换单个字符串中的多个单词?

[英]How to replace multiple words in a single string in Java?

I'm writing a program that will replace multiple words in a single string.我正在编写一个程序,它将替换单个字符串中的多个单词。 I'm using this code but it is replacing word but giving result in two different lines.我正在使用此代码,但它正在替换 word 但在两行不同的行中给出结果。 I want multiple words replaced and output in one single line.我想在一行中替换多个单词和 output。

import java.util.*;
public class ReplaceString {
    public static void main(String[] args) {
        new ReplaceString().run();
    }

    public void run()
    {

        System.out.println("Input String:\n");////
        Scanner keyboardScanner = new Scanner(System.in);/////
        String inString = keyboardScanner.nextLine();/////
        String strOutput = inString.replace("call me","cm");
        System.out.println(strOutput);

        String strOutput1 = inString.replace("as soon as possible","asap");
        System.out.println(strOutput1);      

    }
}

If you want to do it in a single statement you can use:如果您想在单个语句中执行此操作,您可以使用:

String strOutput = inString.replace("call me","cm").replace("as soon as possible","asap");

Alternatively, if you have many such replacements, it might be wiser to store them in some kind of data structure such as a 2d-array.或者,如果您有许多这样的替换,将它们存储在某种数据结构中可能更明智,例如二维数组。 For example:例如:

//array to hold replacements
String[][] replacements = {{"call me", "cm"}, 
                           {"as soon as possible", "asap"}};

//loop over the array and replace
String strOutput = inString;
for(String[] replacement: replacements) {
    strOutput = strOutput.replace(replacement[0], replacement[1]);
}

System.out.println(strOutput);

Of course it prints two lines: you have two print statements.当然它会打印两行:您有两个打印语句。 Use this code:使用此代码:

import java.util.*;

public class ReplaceString {
    public static void main(String[] args) {
        new ReplaceString().run();
    }

    public void run()
    {

        System.out.println("Input String:\n");////
        Scanner keyboardScanner = new Scanner(System.in);/////
        String inString = keyboardScanner.nextLine();/////
        String shortMessage = shortifyMessage(inString);
        System.out.println(shortMessage);
    }

    public String shortifyMessage(String str)
    {
        String s = str;
        s = s.replace("call me", "cm");
        s = s.replace("as soon as possible", "asap");
        // Add here some other replacements

        return s;
    }
}

All above answers could be correct.以上所有答案都可能是正确的。 However, replacing each string once is not efficient.但是,将每个字符串替换一次并不有效。 Following code from Apache Commons StringUtils will help it to efficiently replace all the strings in one go.以下来自 Apache Commons StringUtils 的代码将帮助它有效地替换 go 中的所有字符串。

    System.out.println("Input String:\n");////
    Scanner keyboardScanner = new Scanner(System.in);/////
    String inString = keyboardScanner.nextLine();/////
StringUtils.replaceEach(inString, new String[]{"call me", "as soon as possible"}, new String[]{"cm", "asap"});

Please note that: above method doesn't work on replacing the words in previous substitution result.请注意:上述方法不适用于替换先前替换结果中的单词。 For example:例如:

StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})

will give result: "dcte"将给出结果:“dcte”

Now you can use StringUtils in commons-lang3 package.现在您可以在 commons-lang3 package 中使用 StringUtils。

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.7</version>
</dependency>

Code like below:代码如下:

strOutput = StringUtils.replaceEach(inString, new String[]{"call me", "as soon as possible"}, new String[]{"cm", "asap"});

Use MessageFormat.format(queryString, retrieveArguments().toArray());使用 MessageFormat.format(queryString, retrieveArguments().toArray());

The root problem is that, once you've made the first replacement, you can not work again with the same initially given string.根本问题是,一旦您进行了第一次替换,您就不能再次使用最初给定的字符串。 I think the correct way of doing it would be using different copies and moving from one to the other the content while it is being replaced May be, better than this, the solution could be just do an extra replacement after each done replacement to erase the already replaced patterns.我认为正确的做法是使用不同的副本并在替换内容时从一个副本移动到另一个内容可能比这更好,解决方案可能只是在每次完成替换后进行额外替换以擦除已经替换的模式。 ;) ;)

Instead of using replace use replaceAll which worked for me而不是使用replace使用replaceAll这对我有用

String strOutput = inString.replaceAll("call me","cm").replaceAll("as soon as possible","asap");

Use System.out.print() instead of System.out.println()使用System.out.print()而不是System.out.println()

    String strOutput1 = inString.replace("as soon as possible","asap");

You should change that to你应该把它改成

    String strOutput1 = strOutput .replace("as soon as possible","asap");

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

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