黑马程序员——NSString的几种实用方法

来源:互联网 发布:八宝茶的软件 编辑:程序博客网 时间:2024/05/01 06:57

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

1、NSString创建字符串的常见方式
创建常量字符串:
NSString *str1 = @"This is a String!";
NSString *str2 = [[NSString alloc] initWithString:@"This is a string"];
NSString *str3 = [[NSString alloc] initWithFormat:@"age is %d",10];
NSString *str4 = [[NSString alloc] initWithUTF8String:"age is 10"];
——第二种方式不常用。

2、NSString中最常用的方法

1)length
//求长度int count = [str length];

3)isEqualToString

判断两字符串是否相同
NSString *str0 = @"BBD";  NSString *str1 = @"BBD";        //  字符串完全相等比较  if([str0 isEqualToString:str1])  {          NSLog(@"字符串完全相等");  }  


3.从文件创建字符串
方法1:
NSString *str5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];
方法2:
    NSURL *url1 = [NSURL fileURLWithPath:@"/Users/apple/Desktop/1.txt"];    NSURL *url2 = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/1.txt"];    NSString *s6 = [[NSString alloc] initWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];    NSLog(@"s6=\n%@", s6);


4、characterAtIndex:取出字符串中每个字符(遍历)

<span style="font-size:14px;">        //赋值        NSString *str = @"BBD2008";                //求长度        int count = [str length];                NSLog(@"字符串的长度是%d",count);                //遍历字符串中的每一个字符        for(int i =0; i < count; i++)        {            char c = [str characterAtIndex:i];            NSLog(@"字符串第 %d 位为 %c",i,c);        }  </span>

5、改变英文字符的大小写
    NSString *string1 = @"A String";    NSString *string2 = @"String";    NSLog(@"string1:%@",[string1 uppercaseString]);//全部字符串变为大写    NSLog(@"string2:%@",[string2 lowercaseString]);//全部字符串变为小写    NSLog(@"string2:%@",[string2 capitalizedString]);//将字符串中每个单词的首字母大写


6、在指定位置插入字符串
<span style="font-size:14px;">    NSMutableString *str = [NSMutableString stringWithString:@"this string"];        //在str第5位插入字符串    [str insertString:@"is a " atIndex:5];        NSLog(@"str = %@",str);</span>

7、把一个字符串接在另一个字符串的末尾

    //字符串合并    int i  = 2008;    char*s = "BBD";    NSString *temp = @"temp";        //在字符串temp的基础继续添加s和i    NSString *str4 = [temp stringByAppendingFormat:@"%s%i",s,i];

8、用指定字符串替换字符串中某指定位置、长度的字符串
    NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];        [String1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@"That"];        NSLog(@"String1:%@",String1);

9、删除指定位置指定长度的字符
    NSMutableString *str1 = [[NSMutableString alloc] initWithString:@"This (test) is a NSMutableString"];        [str1 deleteCharactersInRange:NSMakeRange(5, 7)];

10、查找一个子字符串在字符串中的位置

NSRange range1 = [str1 rangeOfString:@"(test) "];




0 0
原创粉丝点击