一,字符串之间比较:
[strA isEqualToString:strB] ; //字符串之间比较:
[A isEqual:B]; //不同类型之间比较:
二,对字符串的操作:
// 去除首尾空格:
mesStr = [mesStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// 去除首尾空格和换行:
mesStr = [mesStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
1,截取a 的某一个部分
NSString *a = @"1.2.30";
NSString *b= [[a substringWithRange:NSMakeRange(4,2)] ; // b = 30
解析如下:substringWithRange: 专门截取字符串的一段
NSMakeRange(4,2) 从第4个字符开始截取,长度为2个字符,(注意:字符串索引值都是从第0个字符开始数的)
2, 字符串截取到第n位 (substringToIndex: n)(注意:第n 位是不包含的)
NSString *a = @"i like long dress";
NSString *b = [a substringToIndex:4]; //b = i li
3,字符串从第n 位开始截取,直到最后 (substringFromIndex:n)(注意:包括第 n 位)
NSString *a = @"i like long dress";
NSString *b = [a substringFromIndex:4]; //b = ke long dress
4,iOS 截取字符串中两个指定字符串中间的字符串
NSString *string = @"<a href=\"http\">这是要截取的内容</a>"
NSRangestartRange = [stringrangeOfString:@"\">"];
NSRangeendRange = [stringrangeOfString:@"</"];
或
NSString*string =@">这是要截取的内容<";
NSRangestartRange = [stringrangeOfString:@">"];
NSRangeendRange = [stringrangeOfString:@"<"];
NSRangerange =NSMakeRange(startRange.location+ startRange.length, endRange.location- startRange.location- startRange.length);
NSString*result = [stringsubstringWithRange:range];
NSLog(@"%@",result); //result = @"这是要截取的内容";
其他:
NSString*str =@""; //长度为0的字符串
NSIntegerstrLength = str.length;
NSString *str2 = [str substringWithRange:NSMakeRange(0, 0)];
NSString *str3 = [str substringWithRange:NSMakeRange(0, 1)]; //crash
NSString*str =nil; //对空字符串操作没反应
NSIntegerstrLength = str.length;
NSString *str2 = [str substringWithRange:NSMakeRange(0, 1)];
三,字符串包含判断:
if ([cityName rangeOfString:city].location == NSNotFound ) { //不包含
}else { //包含 }
字符串包含反包含判断:
if ([cityName rangeOfString:city].location != NSNotFound || [city rangeOfString:cityName].location != NSNotFound) { //包含 … }
四,获得带双引号的字符串:
NSString* str =@"\"你好\""; //str = "你好"
五,计算文字的宽高
NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:17]};
CGSize size1=[@"123" sizeWithAttributes:attrs];
CGSize size2=[@"abc" sizeWithAttributes:attrs];
CGSize size3=[@"赢赢赢" sizeWithAttributes:attrs];
floatweight1 = size1.width;//29
floatweight2 = size2.width;//29
floatweight3 = size3.width;//52
褚小者不可以怀大,绠短者不可以汲深。
网友评论