我想通过仅使用charAt在字符串中找到lastIndexOf字符,但我的代码只查找第一次出现的字符。我需要改变什么?
Scanner sc = new Scanner(System.in);
char operation = sc.nextLine().charAt(0);
if (operation == 'l' ) {
System.out.print("Please enter a string: ");
String enteredString = sc.next();
System.out.print("Please enter a character: ");
char char1 = sc.next().charAt(0);
int index = 1;
for (int i = 0; i < enteredString.length(); i++) {
if (enteredString.charAt(i) == char1) {
index = i;
break;
}
}
System.out.println("The index of character " + char1 + " in string " + enteredString + " is: " + index);
}
我成功地连接了两个String:
Scanner sc = new Scanner(System.in);
char operation = sc.nextLine().charAt(0);
String c = "concatenation";
if (operation == 'c' ) {
System.out.println("Please enter the first string: ");
String firstString = sc.next();
System.out.println("Please enter the scond string: ");
String secondString = sc.next();
for (int i = 0; i < firstString.length(); i++) {
char x = firstString.charAt(i);
System.out.print(x);
}
for (int i = 0; i < secondString.length(); i++) {
char y = secondString.charAt(i);
System.out.print(y);
}
}
问题是,我实际上想要打印这个
System.out.println("The result of concatenating " + firstString + " and " + secondString + " is " + x + y);
但我还没有找到打印方法,因为x和y仅在for循环中定义,如果我尝试打印它,它将被打印多次而不是一次。
当我通过charAt实现子字符串时,这也是一个问题:
if (operation == 's' ) {
System.out.print("Please enter the string: ");
String enteredString = sc.next();
System.out.print("Please enter the first index: ");
int index1 = sc.nextInt();
System.out.print("Please enter the second index: ");
int index2 = sc.nextInt();
for (int i = index1; i < index2; i++) {
char substring = enteredString.charAt(i);
System.out.print(substring);
}
}
我希望打印出来:
System.out.println("The resulting substring is: " + substring);
但我不知道如何实现这一点。
答案 0 :(得分:3)
非常简单:在寻找某个角色的最后出现时 - 只需将字符串向后走。
从 last 字符开始,然后在字符串中“向前”移动。第一场比赛是最后一次。
如果你想保持从0走到字符串末尾的循环:只需记住你正在寻找的那个字符的索引。最初,该索引为-1,并且每次匹配时 - 将其更新为相应的索引。
答案 1 :(得分:1)
正如@GhostCat所说 要查找角色的最后一个索引,只需替换您的代码
int index = 1;
for (int i = 0; i < enteredString.length(); i++) {
if (enteredString.charAt(i) == char1) {
index = i;
break;
}
}
System.out.println("The index of character " + char1 + " in string " + enteredString + " is: " + index);
用这个
int index = -1;
for (int i = enteredString.length() - 1; i >= 0; i--) {
if (enteredString.charAt(i) == char1) {
index = i;
break;
}
}
if (index == -1) {
System.out.println("Character Not Found");
} else {
System.out.println("The index of character " + char1 + " in string " + enteredString + " is: " + index);
}
对于子字符串操作,代码应该是这样的
System.out.print("The resulting substring is: ");
for (int i = index1; i < index2; i++) {
char substring = enteredString.charAt(i);
System.out.print(substring);
}
System.out.println();