簡體   English   中英

修剪字符之間的空格

[英]Trim whitespace in between characters

我剛剛更新為ios 7 sdk,我想修剪/替換字符串字符之間的空格,從而從ABAddressBook中取出數字。

我曾嘗試使用下面的代碼替換“”,但此代碼在ios7 sdk中似乎不起作用,順便說一下,它在ios 6 sdk中工作正常。

NSString *TrimmedNumberField = [self.numberField.text 
stringByReplacingOccurrencesOfString:@" " withString:@""];

在IOS 7中還有其他方法可以做到嗎?

編輯:

我正在嘗試的電話號碼類型。

輸入: "+65 12 345 6789"

我從NSLog獲得的輸出是" 12 345 6789"

我意識到,當我添加到NSDictionary中並在NSLog中查看它時,它似乎包含\\ u00a0的unix代碼表示,類似於“中間的點”,不等於句號。

提前致謝。

這里找到答案

phoneNumber = [phoneNumber stringByReplacingOccurencesOfString:@"." withString:@""];

//其中@“​​。 是通過鍵入Option + 空格鍵創建的

該號碼是從ABAddressbook中提取的。

您可以遍歷字符串並刪除空格,只要有

NSString *someString = @"A string with   multiple spaces and    other whitespace.";

NSMutableString *mutableCopy = [someString mutableCopy];

// get first occurance of whitespace
NSRange range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];

// If there is a match for the whitespace ...
while (range.location != NSNotFound) {
    // ... delete it
    [mutableCopy deleteCharactersInRange:range];
    // and get the next whitespace
    range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
}

// no more whitespace. You can get back to an immutable string
someString = [mutableCopy copy];

上面的字符串的結果是Astringwithmultiplespacesandotherwhitespace.

嘗試這個:

NSString *str = @"   untrimmed   string   ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

嘗試這個

[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

whitespaceCharacterSet iOS的Apple文檔說

返回以二進制格式編碼接收器的NSData對象。

  • (NSData *)bitmapRepresentation返回值一個以二進制格式對接收器進行編碼的NSData對象。

討論此格式適合於保存到文件或以其他方式傳輸或存檔。

字符集的原始位圖表示形式是2 ^ 16位(即8192字節)的字節數組。 位置n的位的值表示十進制Unicode值n的字符存在於字符集中。 要測試原始位圖表示中是否存在帶十進制Unicode值n的字符,請使用以下表達式:

所以試試這個

NSString *testString = @"  Eek! There are leading and trailing spaces  ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
                             [NSCharacterSet whitespaceAndNewlineCharacterSet]];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM