问题
I'm trying to figure out how I can find the index of the last character in the first word in a String variable, while using Scanner class to get the String. In my code I need to use a single String for full name, and find the index of the last character in the first name.
So far I made this:
String fullName;
Scanner s = new Scanner(System.in);
System.out.println("Insert full name: "); //For example: Joseph Adams.
fullName = s.nextLine();
int position = fullName.indexOf(" ");
System.out.println(fullName.substring(0, position));
//I need to find the index of h in Joseph.
回答1:
Find the index of the last character of the first word
Try this.
- the first method subtracts one from the index of the first space which would be the letter
h
. - the second method splits the string into two parts. Part[0] is
joseph
. So theh
is at the length of that string less 1.
String str = "Joseph Adams";
int index = str.indexOf(" ");
if(index < 0) {
index = str.length();
}
System.out.println(index-1);
// or
String[] parts = str.split("\\s+");
int len = parts[0].length();
System.out.println(len-1);
Prints
5
5
回答2:
If there is a space in the input name, the index of the character just before space will be position - 1
; otherwise (i.e. when fullName.indexOf
returns -1
), you can print the index of the last character in the input name and/or do some processing (e.g. print some message) as per your requirement.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Insert full name: "); // For example: Joseph Adams.
String fullName = s.nextLine();
int position = fullName.indexOf(" ");
if (position != -1) {
System.out.println("The index of the character just before space in the input name is " + (position - 1));
} else {
System.out.println("There is no space in the input name.");
System.out.println("The index of the last character in the input name is " + (fullName.length() - 1));
}
}
}
A sample run:
Insert full name: Joseph Adams
The index of the character just before space in the input name is 5
Another sample run:
Insert full name: Joseph
There is no space in the input name.
The index of the last character in the input name is 5
回答3:
The index of the last character in the string is just str.length() - 1
. For example, to find the index of the h
in "Joseph"
:
public static int indexOfLast(String str){
return str.length() - 1;
}
The length of "Joseph"
is 6
but there is no character at index 6
(Strings, like arrays, start with the first element at index 0
). So, we subtract 1
to get 5
, which is the final character in the String. So doing:
String name = "Joseph";
name.charAt(indexOfLast(name));
will return h
.
来源:https://stackoverflow.com/questions/65351199/finding-index-of-last-character-in-an-input-string-java