【问题标题】:How to calculate the number of whitespaces in a String [closed]如何计算字符串中的空格数[关闭]
【发布时间】:2016-11-15 03:59:17
【问题描述】:

我正在尝试通过执行.trim() 方法来删​​除字符串开头的空格。但是,当我尝试计算删除多少空格时,它不起作用。我试过做一个方程: int spaces = line.length() - line.trim().length()。但是由于某种原因,它总是以输入的行的长度结束。我在这里错过了什么吗?还是我的代码的其他部分?

public Squeeze(FileInput inFile, FileOutput outFile)
{
    int spaces = 0;
    String line = "";
    while(inFile.hasMoreLines())
    {
        line = inFile.readLine();
        line = line.trim();
        spaces = line.length() - line.trim().length();
        outFile.println(spaces + line);

    }
    outFile.close();
}

【问题讨论】:

  • 请考虑发布一个不起作用的代码示例。
  • 如果line.length() - line.trim().length(),那是因为line.equals(line.trim())。这就是我们所知道的。
  • 你确定你的字符串有前导空格吗?
  • inFile是什么类型?
  • @codeforester 是的,我有,例如我们放 >> Hello World>Hello World

标签: java string whitespace removing-whitespace


【解决方案1】:

注意: OP 的代码实际上并不计算所有空格,只计算前导空格。对于那些想要直接回答问题的人:

如果你有共同点:

int count = StringUtils.countMatches(yourText, " ");

如果你不这样做:

int count = yourText.length() - yourText.replace(" ", "").length();

以下解决方案仅基于 OP 的代码。

你的问题出在这部分:

line = line.trim();
// At this point, 'line' has already been trimmed.
spaces = line.length() - line.trim().length();

您需要将修剪后的版本放入其他变量中,或者移动line = line.trim() 行直到至少您计算完空格。

public Squeeze(FileInput inFile, FileOutput outFile)
{
int spaces = 0;
String line = "";
String trimmedLine = "";
while(inFile.hasMoreLines())
{
    line = inFile.readLine();
    trimmedLine = line.trim();
    spaces = line.length() - trimmedLine.length();
    outFile.println(Format.left(spaces, 4) + line);

}
outFile.close();
}

【讨论】:

  • 哈!我怀疑这是问题所在,直到 OP 发布了他方便地精简的代码。
  • 这不是意味着他们的输出总是0吗?他们是怎么得到11的?
  • 我们仍然必须遗漏一些代码(因此被否决) - 我假设“空格”行可能不同,但潜在问题可能与此有关。
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多