Below code has variable "name". This may contain first and last name or only first name. This code checks if there is any white space in variable "name". If space exists, then it splits.
However, I am getting the "Error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Space.main(Space.java:9)" during below cases
How to resolve this error.
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
if(name.indexOf(' ') >= 0) {
String[] temp;
temp = name.split(" ");
String fname = temp[0];
String lname = temp[1];
System.out.println(fname);
System.out.println(lname);
} else {
System.out.println("Space does not exists");}
}
}
你必须像这样使用“\\ s”拆分字符串
name.split("\\s+");
If there are two spaces temp[1] will be empty, given "Richard rinse" the array is split this way
1 Richard
2
3 rinse
You should trim()
the string and do something like
while(name.contains(" "))
name=name.replace(" "," ");
String[] parts = name.trim().split("\\s+");
if (parts.length == 2) {
// print names out
} else {
// either less than 2 names or more than 2 names
}
trim
removes leading and trailing whitespace as this lead to either leading or trailing empty strings in the array
the token to split on is a regular expression meaning any series of characters made up of one or more whitespace characters (space, tabs, etc...).
Maybe that way:
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
String tname = name.trim().replace("/(\\s\\s+)/g", " ");
String[] temp;
temp = name.split(" ");
String fname = (temp.length > 0) ? temp[0] : null;
String lname = (temp.length > 1) ? temp[1] : null;
if (fname != null) System.out.println(fname);
if (lname != null) System.out.println(lname);
} else {
System.out.println("Space does not exists");
}
}
To trim the white spaces, use this.
public String trimSpaces(String s){
String str = "";
boolean spacesOmitted = false;
for (int i=0; i<s.length; i++){
char ch = s.chatAt(i);
if (ch!=' '){
spacesOmitted = true;
}
if (spacesOmitted){
str+=ch;
}
}
return str;
}
Then use the trimmed string in the place of name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.