我正在编写一段代码,尝试通过使用用户输入的值之间的空格将用户的输入分成 3 个不同的数组。但是,每次我运行代码时都会收到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
我在输入文本时尝试使用不同的分隔符,效果很好,例如通常使用/拆分完全相同的输入,并执行到目前为止我希望它执行的操作。 任何帮助,将不胜感激! 如果需要的话这是我的代码
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
最佳答案
Split 是一种正则表达式,您可以查找一个或多个空格(“+”),而不仅仅是一个空格(“”)。
String[] array = s.split(" +");
或者您可以使用 Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
关于java - 尝试用空格分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40115106/