删除 Java 中的第一个空格

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

Remove first white space in Java

java

提问by mpluse

How would I remove the first white-space in Java?

我将如何删除 Java 中的第一个空格?

Right now I am using this:

现在我正在使用这个:

if (str.charAt(0) == ' ') str = str.replace(" ", "");

回答by syb0rg

Just use str.trim()to get rid of all leading and trailing spaces.

只是str.trim()用来摆脱所有前导和尾随空格。

回答by Keppil

Use replaceFirst()instead of replace().

使用replaceFirst()代替replace()

TO get rid of all leading spaces you can use

摆脱所有可以使用的前导空格

str = str.replaceFirst("^ *", "");

The ^is just to make sure that the spaces are actually at the start of the string, which it seems like you wanted. If that is not the case, just remove it.

^只是为了确保空格实际上位于字符串的开头,这似乎是您想要的。如果不是这种情况,只需将其删除。

回答by HashHazard

You can use trim()

您可以使用修剪()

newString = stringToTrim.trim();

That will trim both sides of the string... beginning and end.. not sure if that helps.

这将修剪字符串的两侧......开始和结束......不确定这是否有帮助。

More info here... http://docs.oracle.com/javase/7/docs/api/

更多信息在这里... http://docs.oracle.com/javase/7/docs/api/

回答by jahroy

You can also use String.substring().

您还可以使用String.substring()

Invoking s.substring(1)will return everything but the first character the string s.

调用s.substring(1)将返回除字符串第一个字符之外的所有内容s

This works for your specific question, because you only want to remove the first character if it's a space.

这适用于您的特定问题,因为您只想删除第一个字符(如果它是空格)。

if (str.charAt(0) == ' ') {
     str = str.substring(1);
}

回答by Nicholas

Do you want just the first or first and last?

你想要第一个还是第一个和最后一个?

trim()will remove what you want from the beginning and end of string. Otherwise Keppil's answer works.

trim()将从字符串的开头和结尾删除您想要的内容。否则 Keppil 的回答有效。

回答by Tdorno

You could implement the Character.isWhitespacemethod into your code.

您可以在Character.isWhitespace代码中实现该方法。

Link Here: http://msdn.microsoft.com/en-us/library/aa989424(v=vs.80).aspx

链接在这里:http: //msdn.microsoft.com/en-us/library/aa989424(v=vs.80).aspx