比较字符串忽略开头或结尾处的空格
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了比较字符串忽略开头或结尾处的空格相关的知识,希望对你有一定的参考价值。
我是ios开发的新手,我正在寻找一种解决方案来比较两个String,忽略开头或结尾处的空格。例如,“Hello”==“Hello”应该返回true。
我已经搜索过一个解决方案,但我在Swift中找不到任何东西。谢谢
答案
NSString *string1 = @" Hello";
//remove(trim) whitespaces
string1 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *string2 = @"Hello ";
//remove(trim) whitespaces
string2 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@""]
// compare strings without whitespaces
if ([string1 isEuqalToString:string2]) {
}
所以如果你想直接使用它 -
if ([[yourString1 stringByReplacingOccurrencesOfString:@" " withString:@""] isEuqalToString:[yourString2 stringByReplacingOccurrencesOfString:@" " withString:@""]]) {
// Strings are compared without whitespaces.
}
上面将删除你的字符串的所有空格,如果你只想删除前导和尾随空格,那么有几个帖子已经可用,你可以创建一个字符串类别,如下面的堆栈溢出帖子所述 - How to remove whitespace from right end of NSString?
@implementation NSString (TrimmingAdditions)
- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (location; location < length; location++) {
if (![characterSet characterIsMember:charBuffer[location]]) {
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (length; length > 0; length--) {
if (![characterSet characterIsMember:charBuffer[length - 1]]) {
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
@end
现在,一旦你有了可用的方法,你可以在你的字符串上调用这些方法来修剪前导和尾随空格,如 -
// trim leading chars
yourString1 = [yourString1 stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim trainling chars
yourString1 = [yourString1 stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim leading chars
yourString2 = [yourString2 stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim trainling chars
yourString2 = [yourString2 stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// compare strings
if([yourString1 isEqualToString: yourString2]) {
}
另一答案
我建议你先用这个Swift代码修剪字符串中的空格:
stringToTrim.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
另一答案
适用于Swift 3.0+
在比较之前使用.trimmingCharacters(in: .whitespaces)
或.trimmingCharacters(in: .whitespacesAndNewlines)
另一答案
在Swift 4中 在任何String类型变量上使用它。
extension String {
func trimWhiteSpaces() -> String {
let whiteSpaceSet = NSCharacterSet.whitespaces
return self.trimmingCharacters(in: whiteSpaceSet)
}
}
并称之为这样
yourString.trimWhiteSpaces()
以上是关于比较字符串忽略开头或结尾处的空格的主要内容,如果未能解决你的问题,请参考以下文章