NSString基本使用

//*******字符串长度统计*******
//空格也作为一个字符
NSString *string1 = @"iOS is good!";
NSLog(@"%ld", (long)string1.length);//12
//首尾的空格依旧计算在内,tab打印的空格,第一个tab占2个字符,第二个tab占4个字符
NSString *string2 = @" iOS is good! ";
NSLog(@"%ld", (long)string2.length);//14

//*******字符串截取操作*******
//截取字符串 不包括index
NSString *string3 = @"iOS is good!";
NSLog(@"%@", [string3 substringToIndex:2]);//iO
//截取字符串 包括index
NSString *string4 = @"iOS is good!";
NSLog(@"%@", [string4 substringFromIndex:3]);// is good!(第一个输出:空格)
//截取字符串 包括location
NSString *string5 = @"iOS is good!";
NSRange range = NSMakeRange(2, 4);
NSLog(@"%@", [string5 substringWithRange:range]);//S is
//获取字符串中第N个字符
NSString *string6 = @"iOS is good!";
char character = [string6 characterAtIndex:2];
NSLog(@"%c", character);//S

//*******字符串大小写处理*******
//字符串的大小写、首字母大写
NSString *string7 = @"iOS is good!";
NSLog(@"%@, %@, %@", [string7 uppercaseString], [string7 lowercaseString], [string7 capitalizedString]);

//*******字符串之间的操作*******
NSString *stringA1 = @"apple";
NSString *stringB1 = @"banana";
//字符串比较,根据ASCII码表比较(字符相同为0,前者大为1,后者大为-1)
NSLog(@"%ld", (long)[stringA1 compare:stringB1]);//-1
//字符串是否一样
NSLog(@"%ld", (long)[stringA1 isEqualToString:stringB1]);//0
//字符串是否以“”开头
NSLog(@"%ld, %ld", (long)[stringA1 hasPrefix:@"AP"], (long)[stringA1 hasPrefix:@"ap"]);//0, 1
//字符串是否以“”结尾
NSLog(@"%ld, %ld", (long)[stringB1 hasSuffix:@"NA"], (long)[stringB1 hasSuffix:@"banana"]);//0, 1
//字符串拼接
NSLog(@"%@", [stringA1 stringByAppendingString:stringB1]);//applebanana
//用字符串替换指定范围内的字符
NSRange rangeA = NSMakeRange(2, 2);
NSLog(@"%@", [stringA1 stringByReplacingCharactersInRange:rangeA withString:@"iOS"]);//apiOSe
//用字符串替换指定的 字符串 (区分大小写)
NSLog(@"%@", [stringA1 stringByReplacingOccurrencesOfString:@"le" withString:@"LE"]);//appLE

//*******可变字符串操作*******
NSMutableString *muString = [NSMutableString stringWithFormat:@"%@", @"apple"];
//字符串拼接
[muString appendString:@" so delicious"];
NSLog(@"%@", muString);//apple so delicious
//字符串插入
[muString insertString:@"A for apple," atIndex:0];
NSLog(@"%@", muString);//A for apple,apple so delicious
//删除指定范围字符
[muString deleteCharactersInRange:NSMakeRange(0, @"A for apple,".length)];
NSLog(@"%@", muString);//apple so delicious
//替换字符串
NSLog(@"%@", [muString stringByReplacingOccurrencesOfString:@"apple" withString:@"banana" options:NSCaseInsensitiveSearch range:NSMakeRange(0, muString.length)]);//banana so
delicious

你可能感兴趣的:(NSString基本使用)