1 6 去除字串中的空格(trim )

2021-10-09 21:25:29 字數 881 閱讀 8364

字串中存在的首尾空格一般情況下都沒有任何意義,如字串「 hello 」,但是這些空格會影響到字串的操作,如連線字串或比較字串等,所以應該去掉字串中的首尾空格,這需要使用 string 類提供的trim() 方法

字串名.

trim

()

使用 trim() 方法的示例如下:

string str =

" hello "

;system.out.

println

(str.

length()

);// 輸出 7

system.out.

println

(str.

trim()

.length()

);// 輸出 5

從該示例中可以看出,字串中的每個空格佔乙個位置,直接影響了計算字串的長度。

如果不確定要操作的字串首尾是否有空格,最好在操作之前呼叫該字串的 trim() 方法去除首尾空格,然後再對其進行操作

注意:trim() 只能去掉字串中前後的半形空格(英文空格),而無法去掉全形空格(中文空格)。可用以下**將全形空格替換為半形空格再進行操作,其中替換是 string 類的 replace() 方法。

str = str.

replace((

char

)12288

,' ');

// 將中文空格替換為英文空格

str = str.

trim()

;

其中,12288 是中文全形空格的 unicode 編碼。

去除字串中的空格

使用js去除字串內所帶有空格,有以下三種方法 1 replace正則匹配方法 去除字串內所有的空格 str str.replace s g,去除字串內兩頭的空格 str str.replace s s g,去除字串內左側的空格 str str.replace s 去除字串內右側的空格 str str...

去除字串中的空格

利用迭代的思想將字串中的空字元去除 去除字串中的所有空格 deftrim s index 0while index len s if s index if index 0 如果是首字母是空格,直接向後推一位進行迭代 return trim s index 1 len s if index len s...

去除string字串中的空格

很多其他語言的libary都會有去除string類的首尾空格的庫函式,但是標準c 的庫卻不提供這個功能。但是c string也提供很強大的功能,實現trim這種功能也不難。下面是幾種方法 1.使用string的find first not of,和find last not of方法 filenam...