假定以下Java程序以这种方式操纵用户输入的字符串,即用户将决定需要用另一个字符替换哪个字符,而应该替换字符串中的最后一个字符。例如,如果用户输入字符串“ OYOVESTER”并决定将“ O”替换为“ L”,则程序应输出以下结果:“ OYLVESTER”(注意,只有最后一个“ O”被替换为“ L”)
注意:您不能使用BREAK命令来停止循环。禁止。
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
我不断收到以下不正确的输出:
输入要操作的字符串
奥威斯特
输入要替换的字符
的
输入新角色
大号
新句子是:LRETSEVOY
有很多更简单的方法可以满足您的要求,但我希望您必须通过循环(不间断)进行演示。
然后,您可以使用类似以下内容的东西:
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS:不建议在循环中使用String串联,因为每个String串联都会复制整个String,通常最好将其替换为对StringBuilder.append()
或的显式调用StringBuffer.append()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句