如何在Java中替换单个字符串中的多个单词? [英] How to replace multiple words in a single string in Java?

查看:89
本文介绍了如何在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. I want multiple words replaced and output in one single line.

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

或者,如果你有很多这样的替代品,将它们存储在某种数据中可能更明智一些结构如2d阵列。例如:

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

这篇关于如何在Java中替换单个字符串中的多个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆