如何在UI标签中显示时从NSString之间修剪空格

时间:2016-09-19 13:13:56

标签: ios nsstring uilabel

我从web服务获取字符串值。我需要从字符串之间删除空格。我怎样才能做到这一点? 示例:如果字符串为"A ALL YEAR",则在UILabel文本中显示值时,它必须变为"A ALL YEAR"

我附上了下面的图片以供澄清。

enter image description here

3 个答案:

答案 0 :(得分:2)

NSString *yourString = @"A  ALL YEAR";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:@" "];

输出: - 全年

希望你需要这个。如果这不起作用,请告诉我。

答案 1 :(得分:0)

let str = "A All Time".components(separatedBy: " ")

let newString = str[0] + " " + str[1] + " " + str[3]

您也可以使用for循环。

答案 2 :(得分:0)

使用此正则表达式模式尝试\s{2,} 类:

space

并替换为Public Function FN_GET_MONTH(iDays As Long, Optional iDaysInMonth As Long = 30) If (iDays / iDaysInMonth) > iDays \ iDaysInMonth Then FN_GET_MONTH = (iDays \ iDaysInMonth) + 1 Else FN_GET_MONTH = (iDays \ iDaysInMonth) End If End Function ?FN_GET_MONTH(29) = 1 ?FN_GET_MONTH(31) = 2 ?FN_GET_MONTH(60) = 2 ?FN_GET_MONTH(80) = 3 ?FN_GET_MONTH(91) = 4

Regex Demo

NSRegualrExpression for string replacement的示例。