【问题标题】:How to ignore white spaces in Java [duplicate]如何忽略Java中的空格[重复]
【发布时间】:2018-04-24 21:46:25
【问题描述】:

我想知道如何在 Java 中忽略空格。该程序允许您输入您的名字、中间名和姓氏,然后输出您的姓名首字母。我现在正试图让它忽略任何空格。提前致谢!

    String fullName;
    char firstName;
    char secondName;
    char surname;
    int space1;
    int space2;

    System.out.println("Please enter your first name, your second name and your surname: ");
    fullName = kybd.nextLine();

    firstName = fullName.charAt(0);
    space1 = fullName.indexOf(" ");
    secondName = fullName.charAt(space1 + 1);
    space2 = fullName.lastIndexOf(" ");
    surname = fullName.charAt(space2 + 1);

    System.out.println("Initials: " + firstName + secondName + surname);
}

}

【问题讨论】:

  • 只需删除fullName 中的所有空格。例如fullName.replaceAll(" ", "").
  • 目前你的问题有点不清楚。你能给出一些示例输入和预期输出吗?
  • 如果它解决了您的问题,请考虑接受一个答案。这有助于从未回答的问题中过滤答案,谢谢。

标签: java whitespace


【解决方案1】:

说明

您可以通过从输入文本中删除它们来隐式忽略它们。

因此用""(空文本)替换所有匹配项:

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

现在我们识别 firstlast 空白 并将它们分开:

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&lt;Stream&lt;String&gt;&gt; 对象。

【讨论】:

  • 我不确定该代码应该放在哪里,你能告诉我吗?
  • @Smithy98 是的,我编辑了代码,现在更清晰了吗?
  • 这确实有道理,但我在“Bounds”下的 2 行代码出现错误。它说“从 int 到 char 的可能有损转换”。我已将它们声明为字符,但不是 int ..
  • @Smithy98 哦,是的,他们应该是int 不是 char。该方法返回该字符出现的位置,而不是字符
  • 当然!非常感谢您的帮助,它现在可以工作了。我真的很感激!
【解决方案2】:

我想你在这里追求的是split method in String

你可以这样使用:

String fullName = "John Alexander Macdonald";
String[] split = fullName.split(" "); // ["John", "Alexander", "Macdonald"]

您可能想要的另一件事是trim method,它会删除字符串前后的空格。

String withSpaces = " a b c ";
String trimmed = withSpace.trim(); // "a b c"

【讨论】:

  • 用户必须输入自己的名字,所以它不是硬编码的
  • 你仍然可以做fullName.split(" ");我的硬编码字符串只是一个例子。
猜你喜欢
  • 2020-09-27
  • 2011-02-07
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多