如何从单个输入中获取两个字符串(由空格分隔的单词)

时间:2015-11-25 01:02:43

标签: computer-science

我正在尝试从单个输入创建两个字符串。

因此,如果用户输入“John Doe”,我想要两个字符串J和D,其中J = John,D = Doe。

我尝试使用scanner.nextLine()方法但不允许我从单个输入创建两个字符串。

所以基本上我想在用户输入单词之间的空格时创建另一个字符串。

如果有人能为我清楚那将是美妙的!我刚开始学习计算机科学,所以这对我来说都是新的。

2 个答案:

答案 0 :(得分:1)

要从单个输入中获取两个字符串(以空格分隔的单词),请执行以下步骤。

1)首先拆分字符串
2)存储索引
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.
    }
}

答案 1 :(得分:0)

你想要做的是分割一个字符串。假设你使用的是java,你可以简单地把你的字符串做:

(__TEXT,__text) section
_foo1:
0000000100000f10    55                  pushq   %rbp
0000000100000f11    4889e5              movq    %rsp, %rbp
0000000100000f14    897dfc              movl    %edi, -0x4(%rbp)
0000000100000f17    5d                  popq    %rbp
0000000100000f18    c3                  retq
0000000100000f19    0f1f8000000000      nopl    (%rax)
_foo2:
0000000100000f20    55                  pushq   %rbp
0000000100000f21    4889e5              movq    %rsp, %rbp
0000000100000f24    5d                  popq    %rbp
0000000100000f25    c3                  retq
0000000100000f26    662e0f1f840000000000    nopw    %cs:(%rax,%rax)
_main:
0000000100000f30    55                  pushq   %rbp
0000000100000f31    4889e5              movq    %rsp, %rbp
0000000100000f34    4883ec10            subq    $0x10, %rsp
0000000100000f38    488d3d4b000000      leaq    0x4b(%rip), %rdi        ## literal pool for: "Helloooo!\n"
0000000100000f3f    c745fc00000000      movl    $0x0, -0x4(%rbp)
0000000100000f46    b000                movb    $0x0, %al
0000000100000f48    e81b000000          callq   0x100000f68             ## symbol stub for: _printf
0000000100000f4d    bf06000000          movl    $0x6, %edi
0000000100000f52    8945f8              movl    %eax, -0x8(%rbp)
0000000100000f55    e8b6ffffff          callq   _foo1
0000000100000f5a    e8c1ffffff          callq   _foo2
0000000100000f5f    31c0                xorl    %eax, %eax
0000000100000f61    4883c410            addq    $0x10, %rsp
0000000100000f65    5d                  popq    %rbp
0000000100000f66    c3                  retq