【发布时间】:2023-03-14 10:03:01
【问题描述】:
我不允许使用 replace() 方法,我基本上必须让我的程序的一部分来执行此操作:
-要求用户输入要操作的句子。 - 然后要求用户输入要替换的字符(即“hello”中的“e”)。 -然后询问他们希望将其替换为哪个字符。
完成所有这些后,它会将被操纵的字符串输出到屏幕上。
示例:
- 控制台:请输入字符串:
- 用户:你好
- 控制台:请输入要替换的字符:
- 用户:e
- 控制台:请输入一个字符来替换它:
- 用户:l
- 控制台:新字符串是:Hi thlrl
我基本上可以做到这一点,使用这段代码:
int count = 1;
char replaceAll = 'a';
char newChar = 'b';
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String sentence = keyboard.nextLine();
int count = 0;
System.out.println("Enter the character to replace");
replaceAll = keyboard.nextLine().charAt(0);
System.out.println("Enter the new character");
newChar = keyboard.nextLine().charAt(0);
System.out.print("The new sentence is: ");
for(int c = 0; c < sentence.length(); c++){
if(sentence.charAt(c) == replaceAll)
System.out.print(newChar);
else
System.out.print(sentence.charAt(c));
主要问题:唯一的问题是这不会将操作的字符串保存为新字符串。它只会以正确的顺序打印字母以进行输出(一次打印一个字符,而不是一个字符串)。我需要将已操作的字符串(即 Hi thlrl)保存为新字符串,以便之后可以对该新字符串进行更多操作。
【问题讨论】:
标签: java replace char string-parsing