Sportica   Sportica

objective-c 字符串基本操作

1.定义一个字符串a, 截取a 的某一个部分,复制给b, b必须是int型

NSString *a = @"1.2.30";
 
int b= [[a substringWithRange:NSMakeRange(4,2)] intValue];
 
NSLog(@"a:%@  n",a  );
 
NSLog(@"b:%d",b  );
 
解析如下:substringWithRange: 专门截取字符串的一块肉
NSMakeRange(4,2)  从第4个字符开始截取,长度为2个字符,(字符串都是从第0个字符开始数的哦~!)

b = [a intValue]; 将 a 转换为 整数型
 
b = [a floatValue];  将 a 转换为 小数型
 
b = [a boolValue]; 将 a 转换为 布尔型(true /  false)
 
b = [a integerValue]; 将 a 转换为 整数型
 
b = [a longLongValue]; 将 a 转换为 长整型
 
2.字符串截取到第n位  (substringToIndex: n)(第n 位不算再内)

- (void)viewDidLoad
 
{
 
NSString *a = @"i like long dress";
 
NSString *b = [a substringToIndex:4];
 
NSLog(@"n b: %@",b);
 
}
 
3.字符串从第n 位开始截取,直到最后 (substringFromIndex:n)(包括第 n 位)

- (void)viewDidLoad
 
{
 
NSString *a = @"i like long dress";
 
NSString*b = [a substringFromIndex:4];
 
NSLog(@"n b: %@",b);
 
}
 
4.从某一个字符串中的一个字符串开始截取

- (void)viewDidLoad
 
{
 
NSString *a ="/pubic/evdaily.nsf/vwtrymaindocid/8E88469482579180035442A/$file/测试帐号及信息22.docx";
 
NSRange range = [arangeOfString:@"$file/"];//获取$file/的位置
 
NSString *b = [a substringFromIndex:range.location +
range.length];//开始截取
 
NSLog(@"n b: %@",b);
 
}
 

 

 

当NSString为纯数字的时候可以用下面的方法:

//判断是否为整形:

- (BOOL)isPureInt:(NSString*)string{

    NSScanner* scan = [NSScanner scannerWithString:string]; 

    int val; 

    return[scan scanInt:&val] && [scan isAtEnd];

}

//判断是否为浮点形:

- (BOOL)isPureFloat:(NSString*)string{

    NSScanner* scan = [NSScanner scannerWithString:string]; 

    float val; 

    return[scan scanFloat:&val] && [scan isAtEnd];

}


更复杂点的Question:

I have an NSString like so:

@"200hello" or   @"0 something" 

What I would like to be able to do is take the first occuring number in the NSString and convert it into an int.

So that @"200hello" would become int = 200.

and @"0 something" would become int = 0.

Answer1(数字和字符排序不规则):

intvalue; 
BOOL success=[[NSScannerscannerWithString:@"1000safkaj"]scanInteger:&value]; 

If the number is not always at the beginning:

NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; 
int value = [[@"adfsdg1000safkaj" stringByTrimmingCharactersInSet:nonDigits] intValue]; 

Answer2(数字总是在字符前):

If the int value is always at the beginning of the string, you can simply use intValue.

NSString*string=@"123hello"; 

int myInt = [string intValue];

 

 http://www.dkankan.com/archives/4602

posted @ 2013-07-30 10:55  qingjoin  阅读(1494)  评论(0编辑  收藏  举报
  Sportica