黑马程序员技术交流社区
标题:
利用分类给NSString扩展3个方法
[打印本页]
作者:
huh
时间:
2016-1-2 18:08
标题:
利用分类给NSString扩展3个方法
/*
MethodCustom.h
*/
#import <Foundation/Foundation.h>
@interface MethodCustom : NSObject
@end
/*
MethodCustom.m
*/
#import "MethodCustom.h"
@implementation MethodCustom
@end
/*
MethodCustom+Invert.h
*/
#import "MethodCustom.h"
@interface MethodCustom (Invert)
//字符串反转(比如@”123”调用方法后返回@”321”)
-(NSString*)invertString:(NSString *)str;
//计算英文字母的个数(比如@”5435abc54abc3AHJ5”调用方法后返回的是9)
-(int)returnNum:(NSString*)str;
//去除字符串两端空格(比如@” 1235 45 ”调用方法后返回@”1235 45”)
-(NSString*)delSpace:(NSString*)str;
@end
/*
MethodCustom+Invert.m
*/
#import "MethodCustom+Invert.h"
@implementation MethodCustom (Invert)
/*
字符串反转的方法
分析:
1)获得字符串的长度
2)循环求出每个字符,从最后面的字符开始!
3)将求出的字符,放入字符串里面,返回!
str -- 传入的字符串
*/
-(NSString*) invertString:(NSString *)str{
//定义字符串的长度
//sizeof(str);是字节的大小,不是长度!
int len=(int)str.length;
char c;
//定义可变字符串
//NSMutableString *str2=[NSMutableString string];
NSMutableString *str2=[NSMutableString stringWithFormat:@""];
for (int i =0; i<=len; i++) {
c = [str characterAtIndex:len-(i+1)];//取出单个字符
[str2 appendFormat:@"%c",c];//字符串尾部添加字符
}
return str2;
}
/*
计算英文字母的个数(比如@”5435abc54abc3AHJ5”调用方法后返回的是9)
分析:
1)通过ASCII,A-Z(65-90),a-z(97-122)来判断是否为字母,或者直接判断,c>='a'...
2)通过characterAtIndex方法来取出单个字符
3)通过length来确定字符串长度
*/
-(int)returnNum:(NSString*)str{
int count = 0;//字符个数
int len =(int)str.length;
unichar c ;
for (int i=0; i<len; i++) {
c = [str characterAtIndex:i];
//if ((c>=65&&c<=90)||(c>=97&&c<=122)){
if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
count++;
}
}
return count;
}
/*
去除字符串两端空格(比如@” 1235 45 ”调用方法后返回@”1235 45”)
分析:
1)将传进来的字符串,变为可变字符[[NSMutableString alloc] initWithString:str]
2)判断第一个字符是否为空,为空这删除,变成新的可变字符!再次判断此字符串第一个字符是否为空!
3)得到可变字符串的最后的字符(length-1),判断是否为空
*/
-(NSString*)delSpace:(NSString*)str{
NSMutableString *str1 = [[NSMutableString alloc] initWithString:str];
//去除前面空格
while ([str1 characterAtIndex:0] == ' ')
{
[str1 deleteCharactersInRange:NSMakeRange(0, 1)];
NSLog(@"%@\n",str1);
}
//去除后面空格
while ([str1 characterAtIndex:([str1 length] - 1)] == ' ')
{
[str1 deleteCharactersInRange:NSMakeRange(([str1 length] - 1), 1)];
}
return str1;
}
@end
/*
main.m
利用分类给NSString扩展3个方法(Objective-C)
1> 字符串反转(比如@”123”调用方法后返回@”321”)
2> 计算英文字母的个数(比如@”5435abc54abc3AHJ5”调用方法后返回的是9)
3> 去除字符串两端空格(比如@” 1235 45 ”调用方法后返回@”1235 45”)
*/
#import <Foundation/Foundation.h>
#import "MethodCustom.h"
#import "MethodCustom+Invert.h"
int main(int argc, const char * argv[]) {
MethodCustom *mt = [[MethodCustom alloc]init];
NSLog(@"反转后结果为:%@\n",[mt invertString:@"adsffd"]);
NSLog(@"英文字母的个数为:%d",[mt returnNum:@"5435abc54abc3AHJ5"]);
NSLog(@"字母:%@\n",[mt delSpace:@" 1235 45 "]);
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2