java 如何替换空字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1187147/
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-10-29 15:32:44  来源:igfitidea点击:

how to replace the null character

java

提问by Rakesh

In java ,i have editfield whcih takes its input ,in it we can enter 3 digits

在java中,我有editfield whcih接受它的输入,我们可以在其中输入3位数字

when i enter first and third ,leaving 2 digit empty ,how to remove empty digit thanks

当我输入第一个和第三个时,留下 2 个数字为空,如何删除空数字谢谢

回答by Roberto Aguayo Ph D IT

The null character is a character like all others. Its value as a byte is 0. Use \0 to identify it. (Same in C, Perl, C++, C#, etc).

空字符与所有其他字符一样。它作为一个字节的值为 0。使用 \0 来标识它。(在 C、Perl、C++、C# 等中也是如此)。

Java:

爪哇:

String noSpaces = perhapsSpaces.replaceAll("\0", " ");

String noSpaces = perhapsSpaces.replaceAll("\0", " ");

System.out.print(noSpaces + "\n");

System.out.print(noSpaces + "\n");

Perl:

珀尔:

$perhapsSpaces =~ s/\0/ /g;

$perhapsSpaces =~ s/\0/ /g;

print $perhapsSpaces . "\n";

print $perhapsSpaces . "\n";

回答by GaryF

If you want to remove all white space internally in a String (which is what I think you're asking), then you want something like:

如果您想在 String 内部删除所有空格(这就是我认为您要问的),那么您需要以下内容:

sText.replaceAll("\s+", "")

Hope that helps.

希望有帮助。

回答by Mirvnillith

Stripping spaces from a String (don't know if J2ME has StringBuilder so I'll just do ugly String concatenation):

从字符串中去除空格(不知道 J2ME 是否有 StringBuilder 所以我只会做丑陋的字符串连接):

String noSpaces = "";
for (int i=0; i<perhapsSpaces.length(); i++)
{
  if (perhapsSpaces.charAt(i) != ' ')
    noSpaces += perhapsSpaces.charAt(i);
}

For "better" space handling, perhaps Character.isWhitespace?

为了“更好的”空间处理,也许 Character.isWhitespace?

回答by Brian Agnew

If you've got "X_Y" ("_" indicating a missing character) and you want "XY", then

如果你有 " X_Y" (" _" 表示缺少字符) 并且你想要 "XY",那么

String newString = entered.charAt(0) + entered.charAt(2)

is the simplest way. But that's only useful for this one particular case. Do you not want to handle missing beginning and end characters too ?

是最简单的方法。但这仅对这种特殊情况有用。您是否也不想处理丢失的开始和结束字符?