在 UI 标签中显示时,如何在 NSString 之间 trim 空格
How can i trim spaces from between of a NSString while displaying in UI Label
我正在从 Web 获取字符串值 service.I 需要删除字符串之间的空格。我怎样才能做到这一点?
Example:if 字符串是 "A ALL YEAR"
在 UILabel 文本中显示值时必须变为 "A ALL YEAR"
。
我附上了下图以供说明。
let str = "A All Time".components(separatedBy: " ")
let newString = str[0] + " " + str[1] + " " + str[3]
您也可以使用 for 循环。
尝试 NSRegularExpression
class 使用此正则表达式模式:
\s{2,}
并替换为 space
.
NSRegualrExpression for string replacement 的示例。
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:@" "];
输出:- 一整年
希望你需要这个。如果这不起作用,请告诉我。
我正在从 Web 获取字符串值 service.I 需要删除字符串之间的空格。我怎样才能做到这一点?
Example:if 字符串是 "A ALL YEAR"
在 UILabel 文本中显示值时必须变为 "A ALL YEAR"
。
我附上了下图以供说明。
let str = "A All Time".components(separatedBy: " ")
let newString = str[0] + " " + str[1] + " " + str[3]
您也可以使用 for 循环。
尝试 NSRegularExpression
class 使用此正则表达式模式:
\s{2,}
并替换为 space
.
NSRegualrExpression for string replacement 的示例。
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:@" "];
输出:- 一整年
希望你需要这个。如果这不起作用,请告诉我。