【发布时间】:2018-03-17 15:10:43
【问题描述】:
我正在编写一个程序,该程序应该用另一个字母替换单个字母的所有实例。虽然我对代码有一些限制,但我只能使用字符串方法 .length、.substring、.indexOf 和 .equals。我可以使用 + 而不是 .concat 来连接事物。
我现在的问题是,当我将结果打印到程序中时,答案必须包含在变量中。在我意识到这一点之前,我以前使用过这段代码:
if (userCommand.equalsIgnoreCase("replace all")) {
System.out.println("Enter the character to replace");
String replace = keyboard.nextLine();
System.out.println("Enter the new character");
String replaceWith = keyboard.nextLine();
int count = 0;
System.out.print("The new string is: ");
while (lastCharacter >= 0) {
char nextCharacter = userString.charAt(count);
count++;
String nextCharacterString = nextCharacter + "";
if (nextCharacterString.equals(replace)) {
nextCharacterString += replaceWith;
}
System.out.print(nextCharacterString);
lastCharacter--;
}
System.out.println("");
}
如您所见,这会将每个字符一个一个地打印到控制台,而不是作为以后可以操作的变量。我现在使用的代码(它离工作还很远)是:
if (userCommand.equalsIgnoreCase("replace all")) {
System.out.println("Enter the character to replace");
String replaceString = keyboard.nextLine();
char replace = replaceString.charAt(0);
System.out.println("Enter the new character");
String replaceWithString = keyboard.nextLine();
char replaceWith = replaceWithString.charAt(0);
String allLetters = "";
int count = 0;
int indexOfReplacement = 0;
for (int i = 0; i < length; i++) {
char nextCharacter = userString.charAt(count);
count++;
if (replace == nextCharacter) {
indexOfReplacement = count;
nextCharacter = replaceWith;
}
}
String sub1 = userString.substring(0, indexOfReplacement);
System.out.println(sub1);
}
非常感谢任何帮助。
【问题讨论】:
-
那么你的问题是什么?如果您只想保存到变量而不是打印,只需将
System.out.print(...)替换为myVariable = myVariable + ...并将 myVariable 替换为字符串 -
lastCharacter和userString定义在哪里?
标签: java string loops if-statement substring