rosylxf

驾驭命运的舵是奋斗。不抱有一丝幻想,不放弃一点机会,不停止一日努力!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NSString相关用法

Posted on 2012-07-01 16:42  rosylxf  阅读(1560)  评论(0)    收藏  举报
1,字符串的简单用法:
#import
<Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //创建常量字符串 NSString* str=@"This is a string"; //获取字符串的长度 NSUInteger len=[str length]; NSLog(@"length=%lu", len); //result:16 //获取下标为1的字符,用unichar接收 unichar c=[str characterAtIndex:1]; NSLog(@"%c", c); //result:h NSLog(@"%lu", sizeof(unichar)); //result:2 //initWithString初始化字符串 str=[[NSString alloc] initWithString:@"Hello World"]; NSLog(@"%@", str); //result:hello world [str release]; //用标准c字符串创建oc字符串 :initWithCString 方法 str=[[NSString alloc] initWithUTF8String:"This is c string"]; NSLog(@"%@", str); //result:This is c string printf("%s\n", [str UTF8String]); [str release]; str=[NSString stringWithString:@"Hello iOS"]; NSLog(@"%@", str); //result Hello iOS int age=30; //创建格式化字符串。 str=[[NSString alloc] initWithFormat:@"age=%d", age]; NSLog(@"%@", str); [str release]; //stringWithFormat也可用于拼接字符串 str=[NSString stringWithFormat:@"1+1=%d", 1+1]; NSLog(@"%@", str); [pool drain]; return 0; }
2,从文件中读取字符串
 1 #import <Foundation/Foundation.h>
 2 
 3 #define PATH "/Users/lixuefeng/Desktop/dict.txt"
 4 
 5 int main (int argc, const char * argv[]) {
 6     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 7 
 8     NSError* error=nil;
 9     //下面也可用 NSString* path=[NSString stringWithUTF8String:PATH];就不用手动释放path了
10     NSString* path=[[NSString alloc] initWithUTF8String:PATH];
11     
12     /*
13      下面也可用
14      NSString* fileContentString=
15                      [[NSString alloc] 
16                      initWithContentsOfFile:path 
17                      encoding:NSUTF8StringEncoding 
18                      error:&error];
19      
20      但是不要忘了
21      [fileContentString release];
22      */
23     NSString* fileContentString=[NSString
24                 stringWithContentsOfFile:path
25                 encoding:NSUTF8StringEncoding
26                 error:&error];   //如果创建失败,error改变指针指向,指向内部创建的一个NSerror对象
27     
28     [path release];
29     
30     if (nil!=error) {
31         NSLog(@"%@", error);
32         exit(-1);
33     }
34     NSLog(@"%@", fileContentString);
35     
36     [pool drain];
37     return 0;
38 }

3,写入文件到字符串

 

NSString *astring = [[NSString alloc]
                             initWithString:@"This is a String!"];
    NSLog(@"astring:%@",astring);
    NSString *path = @"astring.text";
    [astring writeToFile: path atomically: YES];
    [astring release];

4,重写类描述方法

#import <Foundation/Foundation.h>

@interface Person : NSObject
@end

@implementation Person
#if 1
-(NSString*)description
{
    return @"This is Person's object";
}
#endif 
@end



int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

 
    Person* p=[[Person alloc] init];
    NSLog(@"%@", p);
    [p release];
    
    [pool drain];
    return 0;
}

重写了类描述方法,我们用NSLog(@"%@", p );就会调用我们自己的方法。

调试的时候覆写类描述方法比较有用

5,字符串的比较

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString* str1=@"Hello World";
    NSString* str2=@"hello World";
    
    if([str1 isEqualToString:str2])
    {
        NSLog(@"YES");
    }
    else 
    {
        NSLog(@"NO");
    }
    //compare方法对应的返回值为enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending};
    NSComparisonResult ret=[str1 compare:str2];
    if (NSOrderedAscending==ret) {
        NSLog(@"%@<%@", str1, str2);
    }
    
    if (NSOrderedSame==ret) {
        NSLog(@"%@=%@", str1, str2);
    }
    
    if (NSOrderedDescending==ret) {
        NSLog(@"%@>%@", str1, str2);
    }
    

    [pool drain];
    return 0;
}

6,字符串的截取

 

#import <Foundation/Foundation.h>

NSString* MyStringFromRange(NSRange range)
{
    NSString* str=[NSString 
        stringWithFormat:@"{%lu, %lu}", 
                   range.location, range.length];
    return str;
}
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   
    NSString* str1=@"this is a string";
    NSString* str2=@"string";
    NSRange range;
    //判断一个字符串中是否包含有另外一个字符串,并返回str2再str1中得位置和长度
    range=[str1 rangeOfString:str2];
    
    if(range.location!=NSNotFound) //
    {
#if 0
        NSLog(@"loc:%lu, len:%lu",
              range.location, range.length );
#endif
        //NSLog(@"%@", NSStringFromRange(range));
        NSLog(@"%@", MyStringFromRange(range));
    }
    
    //iPhone, iPad, iTV, iOS, iMac
    str1=@"Hello, iOS";
    //判断字符串中是否包含前缀或着后缀。
    [str1 hasPrefix:@"Hello"] == YES ?NSLog(@"YES Hello") : NSLog(@"NO");
    [str1 hasSuffix:@"iOS"] == YES ?NSLog(@"YES iOS") : NSLog(@"NO");
    
    //截取字符串
    //-substringFromIndex: 以指定位置开始(包括指定位置的字符),并包括之后的全部字符
    //-substringToIndex: 从字符串的开头一直截取到指定的位置,但不包括该位置的字符
    //-substringWithRange: //按照所给出的位置,长度,任意地从字符串中截取子串
    str2=[str1 substringFromIndex:7];
    NSLog(@"%@", str2);
    NSLog(@"%@", str1);
    
    str2=[str1 substringToIndex:5];
    NSLog(@"%@", str2);
    
    
    //range=(NSRange){3, 2};
    range=NSMakeRange(3, 2);
    str2=[str1 substringWithRange:range];
    NSLog(@"%@", str2);
    
    [pool drain];
    return 0;
}

 

运行结果:

 

2012-06-24 13:33:46.107 demo8[1606:707] {10, 6}

2012-06-24 13:33:46.109 demo8[1606:707] YES Hello

2012-06-24 13:33:46.110 demo8[1606:707] YES iOS

2012-06-24 13:33:46.111 demo8[1606:707] iOS

2012-06-24 13:33:46.111 demo8[1606:707] Hello, iOS

2012-06-24 13:33:46.112 demo8[1606:707] Hello

2012-06-24 13:33:46.112 demo8[1606:707] lo