[英]How to get two strings from a single input (words separated by a space)
I am trying to create two strings from a single input. 我试图从单个输入创建两个字符串。
So if the user inputs "John Doe" I want to have two strings J and D where J=John and D=Doe. 因此,如果用户输入“ John Doe”,我想拥有两个字符串J和D,其中J = John和D = Doe。
I tried using the scanner.nextLine() method but that won't let me create two strings from the single input. 我尝试使用Scanner.nextLine()方法,但这不能让我从单个输入创建两个字符串。
So essentially I want to create another string whenever the user inputs a space between words. 因此,基本上我想在用户输入单词之间的空格时创建另一个字符串。
If anyone can clear that up for me that would be wonderful! 如果有人能为我解决问题,那就太好了! I have just started studying computer science so this is all new to me.
我刚刚开始学习计算机科学,因此这对我来说是全新的。
To get two strings from a single input (words separated by a space) follow this step. 要从单个输入中获取两个字符串(单词之间用空格隔开),请执行以下步骤。
1) First of all split the string 1)首先拆分字符串
2) store with index 2)存储索引
3) print with single space 3)用单个空格打印
public class SpaceRemove {
public static void main(String[] args) {
String s = "The java is best";
String[] temp3 = s.split("\\s+"); // First step
String a, b, c, d;
a = temp3[0]; // Store "The" at index 0
b = temp3[1]; // Store "java" at index 1
c = temp3[2]; // Store "is" at index 2
d = temp3[3]; // Store "best" at index 3
for (String string : temp3) {
System.out.println(" " + string.trim()); // Print the split string
}
System.out.println("You input: " + a + " " + b + " " + c + " " + d); // Print the result with equal space
// between two string.
}
}
What you want to do is split a string.Im assuming you are using java you can simply take your string and do: 你要做的是分割一个字符串。我假设你正在使用Java,你可以简单地把你的字符串做为:
String ex = "John Doe";
String[] parts = String.split(ex);
String part1 = array[0];
String part2 = array[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.