您可以通過使用NSCharacterSet
和componentsSeparatedByString
做到這一點。
解決方案:
// Your string
NSString *myString = @"Name: Tom Smith Old address street name : 31 Fox Road Dixton 0000";
// Seperating words which have more than 1 space with another word
NSArray *components = [myString componentsSeparatedByString:@" "];
NSString *newString = @"";
NSString *oldString = @"";
for (NSString *tempString in components)
{
// Creating new string
newString = [oldString stringByAppendingString:[tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
// Avoiding new line characters or extra spaces contained in the array
if (![oldString isEqualToString:newString])
{
newString = [newString stringByAppendingString:@"\n"];
oldString = newString;
}
}
NSLog(@"%@",newString);
或
您可以使用NSRegularExpression
NSString *pattern = [NSString stringWithFormat:@" {2,%d}",[myString length]];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSString *output = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:@"\n"];
NSLog(@"%@", output);
你檢查嗎? http://stackoverflow.com/questions/6608420/how-to-remove-whitespace-in-a-string – MrBr
@ MrBr我有,它不給我那個非常相同的期望輸出 –
這需要更多的信息..是你試圖在標籤上顯示這個字符串?你得到的產量是多少?並且是這個字符串硬編碼或你得到它像這樣從一些web服務? –