仅使用循环,我将如何替换所有出现的单词?

问题描述 投票:0回答:1

我知道Java具有replace方法,但是我试图弄清楚如何做到这一点。到目前为止,我的代码使我能够替换一个单词,但不能替换所有出现的单词。 someString,word1和word2都是用户在main方法中输入的字符串。

示例输入:狗在另一只狗的猫身上吠叫

示例输出:猫吠叫在另一只猫上

import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
    System.out.println("ID003");

    Scanner input = new Scanner(System.in);
    // Prompt user to input a string
    System.out.print("Enter a string: ");
    String someString = input.nextLine();
    // Prompt user to input a word to be replaced
    System.out.print("Enter Word 1 (to be replaced): ");
    String word1 = input.nextLine();
    // Prompt user to input a word to replace word1
    System.out.print("Enter Word 2 (that replaces Word 1): ");
    String word2 = input.nextLine();

    // Part 1 - display results using replace() string method
    String part1 = someString.replace(word1, word2);
    System.out.println("Part 1");
    System.out.println(part1);

    // Part 2 - display results using only loops * calls on replaceWord method
    System.out.println("Part 2");
    System.out.println(replaceWord(someString, word1, word2));

    }
    // Part 2 - Other replaceWord method
    public static String replaceWord(String someString, String word1, String word2){
        // Declare initial variables
        String temp = "";
        String replacedString = "";
        int remainingString = 0;

        // Loop to run through the entire string
        for (int i = 0; i < someString.length() - word1.length(); i++){
            temp = someString.substring(i, i + 1);

            // Replace substrings with replaced word
            if (someString.substring(i, i + word1.length()).equals(word1)){
                temp = word2 + " ";
                i += word1.length();
            }
            remainingString = i;
            replacedString += temp;
        }
        // Adds replacements to new string
        replacedString += someString.substring(remainingString + 1, someString.length());
        // Returns the final string
        return replacedString;
    }
}
java string loops variables methods
1个回答
0
投票

如果要替换单词,则可以使用此方法

public static String replaceWord(String someString, String word1, String word2){
    String[] words = someString.split(" ");
    String result = "";
    for (String w:words){
        if (w.equals(word1)){
            result+=" "+word2;
        }else{
            result+=" "+w;
        }

    }
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.