??今天ui設計師小妹,在矯正ui。突然對我說,嘿,你這條數據怎么間距這么大。我一看不對呀,就是一個Recyclerview,然后每個Item理論上是一致的呀。怎么就這條數據跟別人不一樣呢?然后,我就看了看數據,果然服務器返回數據中帶了一個特殊的符號,那就是\r\n.哎呀,媽呀,換行符號。怪不得我的那個Item跟下面間距多了一行。
??好的,問題定位了,就是服務器返回多了一個換行符號。本想說這個是服務器返回數據的問題。可是ui小妹不妥協,必須要改,影響ui美觀。那咱就改吧,畢竟我們都是認真的人,哈哈哈。然后我就想將這種符號直接替換成空字符串""就好了嘛。然后我就寫了stringA.replace("\r\n","");運行了一遍可是效果沒出來,依然間距很大。很是納悶。那就試試,replaceAll吧,然后就好使了。那就比較疑惑了,為什么一個好使,另外一個就不行呢?那就得看看兩者的區別了。
??replace(CharSequence target, CharSequence replacement)方法,sdk中解釋如下:
/**
* Returns a copy of this string after replacing occurrences of {@code target} replaced
* with {@code replacement}. The string is processed from the beginning to the
* end.
*
* @throws NullPointerException
* if {@code target} or {@code replacement} is {@code null}.
*/ ```
  大意就是這個方法將會返回一個將target出現的地方都會被替換為replacement的復本。這種替換是從開始到結束的。當然如果被替換字符或者替換字符的傳入為null,是會拋出空指針異常的啦。
  然后我們看看replaceAll(String regularExpression, String replacement)在sdk中的解釋:
/**
* Replaces all matches for {@code regularExpression} within this string with the given
* {@code replacement}.
* See {@link Pattern} for regular expression syntax.
*
* <p>If the same regular expression is to be used for multiple operations, it may be more
* efficient to reuse a compiled {@code Pattern}.
*
* @throws PatternSyntaxException
* if the syntax of the supplied regular expression is not
* valid.
* @throws NullPointerException if {@code regularExpression == null}
* @see Pattern
* @since 1.4
*/ ```
??一看,還真的是有所發現,你看第一個被替換的參數是regularExpression正則表達式呀,然后我又突然想到了,我用replace方法時候我是將替換后的字符串打印了出來的,當時是有看到我要替換的\r\n是沒有了即被替換為了“”。但是它帶來的格式還在,就是換行效果是還在的。然后又看到replaceAll方法的解釋,就明白了,因為\r\n是轉義字符,所以單純的替換字符串是不行的。所以要用replaceAll方法,是以正則表達式來替換的,是有格式的校驗的。
??以上如有不對之處,歡迎批評指正。