在Java中修剪字符串的正确方法 [英] Correct way to trim a string in Java

查看:46
本文介绍了在Java中修剪字符串的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我这样做是为了修剪字符串:

In Java, I am doing this to trim a string:

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.trim();
System.out.println("after->>"+input+"<<-");

输出为:

before->> some Thing <<-
after->>some Thing<<-

工作.但是我想知道是否通过给自己分配一个变量来做正确的事情.我不想通过创建另一个变量并为其分配修剪后的值来浪费资源.我想就地进行修剪.

Works. But I wonder if by assigning a variable to itself, I am doing the right thing. I don't want to waste resources by creating another variable and assigning the trimmed value to it. I would like to perform the trim in-place.

那么我这样做正确吗?

推荐答案

您做对了.来自文档:

字符串是常量;它们的值在创建后无法更改.字符串缓冲区支持可变字符串.由于String对象是不可变的,因此可以共享.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

也来自文档:

修剪

公共字符串trim()

public String trim()

返回字符串的副本,带有前导和尾随空格省略.如果此String对象表示一个空字符序列,或由表示的字符序列的第一个和最后一个字符此String对象的代码均大于'\ u0020'(空格字符),然后返回对此String对象的引用.

Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

否则,如果没有字符的代码大于"\ u0020"在字符串中,然后是一个新的String对象,表示一个空字符串创建并返回.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

否则,令k为字符串中第一个字符的索引其代码大于"\ u0020",并令m为该对象的索引字符串中代码大于'\ u0020'的最后一个字符.一种创建了新的String对象,表示该对象的子字符串以索引k处的字符开始并以索引m处的字符,即this.substring(k,m + 1)的结果.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

此方法可用于从字符串的开头和结尾.

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

返回:

此字符串的副本,其中删除了前导空格和尾随空格;如果没有前导空格或尾随空格,则返回此字符串空间.

A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

这篇关于在Java中修剪字符串的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆