2、NSString *log=@"北京欢迎您a"; //[NSString stringWithFormat:@"I am ‘%@‘",Beijing]; //字符串格式化
3、NSString *zhui = [Beijing stringByAppendingString:@"哈哈哈"]; //字符串追加
4、bool b=[Beijing isEqualToString:log]; //字符串比较
5、NSString *hh = @"http://www.sina.com.cn";
if([hh hasPrefix:@"http"]){ //查找以http开头的字符串
NSLog(@"含有http");
}else{
NSLog(@"没有http");
}
6、 NSString *ss = @"123";
int a = [ss intValue]+13; //字符串转int型
double dd = [ss doubleValue]+33.3; //字符串转double型
NSLog(@"%g",dd);
7、字符串转数组
NSString *zifuchuan =@"one,two,three,four";
NSLog(@"string:%@",zifuchuan);
NSArray *array = [zifuchuan componentsSeparatedByString:@","];
// NSLog(@"array:%@",array); //输出整个数组中所有元素
NSString *value = [array objectAtIndex:0]; //取出第0个元素
NSLog(@"value:%@",value);
8、//数组转字符串
NSString * zifuchuan2 = [array componentsJoinedByString:@","];
NSLog(@"zifuchuan2:%@",zifuchuan2);
结果:zifuchuan2:one,two,three,four
9、-substringToIndex: 从字符串的开头一直截取到指定的位置,但不包括该位置的字符
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringToIndex:3];
NSLog(@"string2:%@",string2);
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringFromIndex:3];
NSLog(@"string2:%@",string2);
NSString *string1 = @"This is a string";
NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 4)];
NSLog(@"string2:%@",string2);
结果:string2:This
//去除字符串中用括号括住的位置
-(NSString *)handleStringWithString:(NSString *)str{
NSMutableString * muStr = [NSMutableString stringWithString:str];
while (1) {
NSRange range = [muStr rangeOfString:@"("];
NSRange range1 = [muStr rangeOfString:@")"];
if (range.location != NSNotFound) {
NSInteger loc = range.location;
NSInteger len = range1.location - range.location;
[muStr deleteCharactersInRange:NSMakeRange(loc, len + 1)];
}else{
break;
}
}
return muStr;
}
NSMutableString *mstr = [[NSMutableString alloc] init];实例话一个可变字符串;
NSString *str1 = @"This is a example.";
//创建可变字符串
mstr = [NSMutableString stringWithString:str1];
//插入字符
[mstr insertString:@"very easy " atIndex:10];
NSRange substr = [mstr rangeOfString:@"example"]; //字符串查找,可以判断字符串中是否有
if (substr.location != NSNotFound) {
[mstr deleteCharactersInRange:substr];
}
//重新设置字符串
[mstr setString:@"This is string AAA"];
//替换字符串
[mstr replaceCharactersInRange:NSMakeRange(15, 2) withString:@"BBB"]; //从第15个字符串处替换掉后2个字符串
结果:2015-08-19 16:54:14.757 Demo[94216:4715472] This is string BBBA
NSString *search = @"This is";
NSString *replace = @"An example of";
substr = [mstr rangeOfString:search];// substr类型为nsrange;
if (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace]; //把第1个遇到的substr替换为replace
NSLog(@"%@",mstr);
}
//rangeOfString 前面的参数是要被搜索的字符串,后面的是要搜索的字符
//NSNotFound 表示请求操作的某个内容或者item没有发现,或者不存在
//查找全部匹配的,并替换
search = @"a";
replace = @"X";
substr = [mstr rangeOfString:search];
while (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
substr = [mstr rangeOfString:search];
}
NSLog(@"%@",mstr);