[英]Java String operations by only using charAt (lastIndexOf, concatenate, substring, contain)
我想仅通过使用charAt在String中找到字符的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到字符串末尾的循环:只需记住要查找的char的索引。 最初,该索引为-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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.