首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

NSString有关用法

2012-09-19 
NSString相关用法1,字符串的简单用法:#import Foundation/Foundation.hNSString* MyStringFromRange(NSR

NSString相关用法

1,字符串的简单用法:

#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 0NSLog(@"loc:%lu, len:%lu",  range.location, range.length );#endif//NSLog(@"%@", NSStringFromRange(range));NSLog(@"%@", MyStringFromRange(range));}//iPhone, iPad, iTV, iOS, iMacstr1=@"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

热点排行