说明
您可以通过从输入文本中删除它们来隐式忽略它们。
因此用""(空文本)替换所有匹配项:
fullName = fullName.replaceAll(" ", "");
在调用 fullName 之后,将不再包含 空格。
但是,当您在 空格 上拆分时,您的逻辑会出现问题。
解决方案
另一种方法是先trim 文本(删除前导和尾随 空格)。然后进行拆分,然后您可以删除所有其他 空格:
fullName = kybd.nextLine();
// Remove leading and trailing whitespaces
fullName = fullName.trim();
// Bounds
firstSpace = fullName.indexOf(" ");
lastSpace = fullName.lastIndexOf(" ");
// Extract names
String fullFirstName = fullName.substring(0, firstSpace);
String fullSecondName = fullName.substring(firstSpace + 1, lastSpace);
String fullSurname = fullName.substring(lastSpace + 1);
// Trim everything
fullFirstName = fullFirstName.trim(); // Not needed
fullSecondName = fullSecondName.trim();
fullSurname = fullSurname.trim();
// Get initials
firstName = fullFirstName.charAt(0);
secondName = fullSecondName.charAt(0);
surname = fullSurname.charAt(0);
示例
让我们看一个示例输入(_ 代表 空格):
__John___Richard_Doe_____
我们将首先trim fullName 从而得到:
John___Richard_Doe
现在我们识别 first 和 last 空白 并将它们分开:
First name: John
Second name: ___Richard
Surname: _Doe
最后我们还修剪一切并得到:
First name: John
Second name: Richard
Surname: Doe
我们使用charAt(0) 访问缩写:
First name: J
Second name: R
Surname: D
更有活力
另一种更动态的方法是将所有连续空格合并为一个单个空格。因此,您需要从左到右遍历文本并在看到空格后开始 recording,如果访问非空格字符则结束 recording,然后将该部分替换为一个空格。
我们的例子是:
_John_Richard_Doe_
在额外的trim 之后,您可以再次使用常规方法:
John_Richard_Doe
或者你可以使用split(" ")然后reject每个empty String:
Iterator<String> elements = Pattern.compile(" ").splitAsStream(fullName)
.filter(e -> !e.isEmpty()) // Reject empty elements
.collect(Collectors.toList()) // Collect to list
.iterator() // Iterator
firstName = elements.next().charAt(0);
secondName = elements.next().charAt(0);
surname = elements.next().charAt(0);
再次使用该示例,Stream 首先包含
"", "", "John", "", "", "Richard", "Doe", "", "", "", "", ""
过滤后是
"John", "Richard", "Doe"
减号
如你所说,你也想要
Richard Jack Smith-Adams
输出RJS-A,在空格上拆分后,你可以简单地在-上拆分。
Pattern spacePatt = Pattern.compile(" ");
Pattern minusPatt = Pattern.compile("-");
String result = spacePatt.splitAsStream(fullName) // Split on " "
.filter(e -> !e.isEmpty()) // Reject empty elements
.map(minusPatt::splitAsStream) // Split on "-"
.map(stream ->
stream.map(e -> e.substring(0, 1))) // Get initials
.map(stream ->
stream.collect(Collectors.joining("-"))) // Add "-"
.collect(Collectors.joining("")); // Concatenate
哪个输出RJS-A。
这种方法有点复杂,因为我们需要维护子流的信息,我们不能把flatMap全部放在一起,否则我们不知道在哪里再添加-。所以在中间部分,我们确实在操作Stream<Stream<String>> 对象。