如果我的问题难以理解,我很抱歉,英语不是我的主要语言,希望你们能够容忍我的英语。我正在编写一个代码,用于读取用户输入的文本并将某些单词转换为全部大写,例如nice变为NICE。 nice这个词可以是大小写的组合,比如Nice NIce NICe NiCE NicE NiCe nICe nicE等等,并且在那些“不错”的结尾会转换成NICE。由于“好”字的组合很多,我将初始输入文本设置为全部小写,并用NICE替换“nice”。我现在遇到的问题是我不知道如何打印出最终结果,这是很好的单词转换为NICE。我现在正在编写的程序正在按1进行转换。如果我的字符串输入中有很多“好”字,那么这很长。有没有更好的方法呢?非常感谢你。这是我的代码
import java.util.Scanner;
public class Substitute
{
public static void main (String[] args)
{
String search = "nice";
String sub = "NICE";
String result = "";
int i;
Scanner input = new Scanner(System.in);
String yourSentence;
System.out.print("enter your text here: ");
yourSentence = input.nextLine();
String actualWord = yourSentence.toLowerCase();
do
{
System.out.println(actualWord);
i = actualWord.indexOf(search);
if (i != -1)
{
result = actualWord.substring(0,i);
result = result + sub + actualWord.substring(i + search.length());
actualWord = result;
}
} while (i != -1);
}
}
这是
my output --------------------Configuration: <Default>--------------------
enter your text here: be nice to your families and be NicE to your friends too. Also be NICe to everyone in this world
be nice to your families and be nice to your friends too. also be nice to everyone in this world
be NICE to your families and be nice to your friends too. also be nice to everyone in this world
be NICE to your families and be NICE to your friends too. also be nice to everyone in this world
be NICE to your families and be NICE to your friends too. also be NICE to everyone in this world
Written by blabla
Process completed.
答案 0 :(得分:3)
yourSentence.replaceAll("(?i)nice", "NICE");
答案 1 :(得分:0)
你可以使用正则表达式,当你想要替换多个东西时非常有用,这里有一个好的,坏的和丑的样本:)。
String inputText = "your text.....";
Pattern searchPattern = Pattern.compile( "nice|bad|ugly", PATTERN_CASE_INSENSITIVE );
Matcher m = searchPattern.matcher( inputText );
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
答案 2 :(得分:-2)
这应该可以解决您的问题。
Scanner input = new Scanner(System.in);
//Convert the Scanner object to a String
String str = input.toString();
//Get the beginning index for "nice"
int begin = str.indexOf("nice");
//Get the ending index for "nice"
int end = str.indexOf(" ", begin );
//Replace the string between begin and end with NICE
str.replace("nice", "NICE");