java 用空格替换制表符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41453983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:53:31  来源:igfitidea点击:

Replace tab with blank space

javatabs

提问by ChosenForWorlds

final String remove = "   " // tab is 3 spaces

while (lineOfText != null)
   {
       if (lineOfText.contains(remove))
       {
           lineOfText = " ";
        }
       outputFile.println(lineOfText);
       lineOfText = inputFile.readLine();
   }

I tried running this but it doesn't replace the tabs with one blank space. Any solutions?

我尝试运行它,但它不会用一个空格替换选项卡。任何解决方案?

回答by Elliott Frisch

Tab is not three spaces. It's a special character that you obtain with an escape, specifically final String remove = "\t";and

Tab 不是三个空格。这是一个特殊的字符,你有逃生获得,特别是final String remove = "\t";

if (lineOfText.contains(remove))
    lineOfText = lineOfText.replaceAll(remove, " ");
}

or remove the if(because replaceAlldoesn't need it) like,

或删除if(因为replaceAll不需要它)像,

lineOfText = lineOfText.replaceAll(remove, " ");

回答by Daniel Plaku

You can simply use this regular expression to replace any type of escapes( including tabs, newlines, spaces etc.) within a String with the desired one:

您可以简单地使用此正则表达式将字符串中的任何类型的转义符(包括制表符、换行符、空格等)替换为所需的转义符:

lineOfText.replaceAll("\s", " ");

Here in this example in the string named lineOfTextwe have replaced all escapes with whitespaces.

在此示例中,在名为lineOfText的字符串中,我们已将所有转义符替换为空格。