如何在Java中仅将确切单词”ants”替换为”bugs”?

huangapple go评论87阅读模式
英文:

how can i replace the exact word ants to bugs only in Java

问题

import java.util.Scanner;

public class TextProcessing {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = sc.nextLine();

        Scanner sc1 = new Scanner(System.in);
        System.out.print("Enter a replacement: ");
        String replacement = sc1.nextLine();

        Scanner sc2 = new Scanner(System.in);
        System.out.print("Enter a word to replace: ");
        String wordToReplace = sc2.nextLine();

        // Split the sentence into words
        String[] words = sentence.split(" ");
        StringBuilder result = new StringBuilder();

        // Iterate through the words
        for (String word : words) {
            // Check if the word matches the word to replace
            if (word.equals(wordToReplace)) {
                // If it matches, append the replacement word
                result.append(replacement).append(" ");
            } else {
                // If it doesn't match, append the original word
                result.append(word).append(" ");
            }
        }

        // Print the sentence with the strings replaced
        System.out.println(result.toString().trim());
    }
}

This code will replace all occurrences of a word in a sentence with another word while ensuring that only exact matches are replaced.

英文:

如何在Java中仅将确切单词”ants”替换为”bugs”?

  1. Write a file named TextProcessing.java that will replace all occurrences of a word in a string with another word. You file should ask user to enter a sentence, then ask the user to enter the two strings where the first one is the word you like to replace and the second is the word you like to replace with. At the end, you file should print out the sentence with the strings replaced.

Please pay attention the String method replace() will replace all the occurrences, however, we require to replace the exact word only. Therefore, you need carefully check the words before your replace them.

As an example, given the sentence “The ants are crossing the road”, your method should be able to replace the word “ants” with another word, like “pigs.”

But if the sentence is:

“The ants are crawling down the pants”, your method should replace the word “ants” with another word, but it should NOT replace the word “ants” in the word “pants.”

Write pseudocode to show your programming logic before you start coding.

Test your file with sentence “The ants are crawling down the pants”, and you need replace ‘ants’ with ‘bugs’.

here is the code that i tried

import java.util.Scanner;
public class text {

    
    public static void main(String[] args) {
	
	Scanner sc= new Scanner(System.in);
	System.out.print("Enter a sentence ");
	String str1= sc.nextLine(); 
	
	Scanner sc1= new Scanner(System.in);
	System.out.print("Enter a repleacemnet ");
	String str2= sc1.nextLine();
	
	
	Scanner sc2= new Scanner(System.in);
	System.out.print("Enter a word to repleace ");
	String str3= sc2.nextLine();
	
	
	str4=str1.repleace(str2,str3);
	
	System.out.print(str4);
	
	}
}

It turns out error:

text.java:21: error: cannot find symbol
        str4=str1.repleace(str2,str3);
        ^
  symbol:   variable str4
  location: class text
text.java:21: error: cannot find symbol
        str4=str1.repleace(str2,str3);
                 ^
  symbol:   method repleace(String,String)
  location: variable str1 of type String
text.java:23: error: cannot find symbol
        System.out.print(str4);
                         ^
  symbol:   variable str4
  location: class text
3 errors

答案1

得分: 0

首先,每次需要输入时都创建一个新的扫描器对象是不必要的。在获取所有必要的输入之后,此代码将句子拆分为一个字符串数组,每个单词都在流中,然后如果单词等于str3,则将每个单词替换或按原样返回。最后,流的结果被连接成一个字符串,保存在str1中,然后进行打印。

import java.util.*;
import java.util.stream.Collectors;

class text {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入一个句子:");
        String str1 = sc.nextLine();

        System.out.print("输入一个替换词:");
        String str2 = sc.nextLine();

        System.out.print("输入一个要替换的单词:");
        String str3 = sc.nextLine();

        str1 = Arrays.stream(str1.split(" "))
                     .map(s -> {
                         if (s.equals(str3))
                            return s.replace(str3, str2);
                         return s;
                     }).collect(Collectors.joining(" "));

        System.out.print(str1);
    }
}

输出:

输入一个句子:The ants are crawling down the pants
输入一个替换词:bugs
输入一个要替换的单词:ants
The bugs are crawling down the pants
英文:

At first, making a new scanner object every time input is required, is not necessary. After all the necessary input is acquired, this code splits the sentence into a string array of words in the stream, and then each word is either replaced, if it is equal to str3, or is returned as-is. Finally the results of the stream are joined into a string, which is saved in str1, and then printed.

import java.util.*;
import java.util.stream.Collectors;

class text {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence ");
        String str1 = sc.nextLine();

        System.out.print("Enter a replacement ");
        String str2 = sc.nextLine();

        System.out.print("Enter a word to replace ");
        String str3 = sc.nextLine();

        str1 = Arrays.stream(str1.split(" "))
                     .map(s -> {
                         if (s.equals(str3))
                            return s.replace(str3, str2);
                         return s;
                     }).collect(Collectors.joining(" "));

        System.out.print(str1);
    }
}

Output:

Enter a sentence The ants are crawling down the pants
Enter a replacement bugs
Enter a word to replace ants
The bugs are crawling down the pants

huangapple
  • 本文由 发表于 2020年10月7日 16:19:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64240023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定