删除 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
Remove first white space in 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
回答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

