利用分类给NSString扩展3个方法(Objective-C)
1> 字符串反转(比如@”123”调用方法后返回@”321”)2> 计算英文字母的个数(比如@”5435abc54abc3AHJ5”调用方法后返回的是9)
3> 去除字符串两端空格(比如@”1235 45 ”调用方法后返回@”1235 45”)
解题方法:
//
// NSString+Turnback.h
//
// 将字符串反转(比如@”123”调用方法后返回@”321”)
#import <Foundation/Foundation.h>
@interface NSString (Turnback)
+ (NSString *)doturnback:(NSString *)str;
@end
//
// NSString+Turnback.m
//
#import "NSString+Turnback.h"
@implementation NSString (Turnback)
+ (NSString *)doturnback:(NSString *)str
{
NSMutableString *str1 = [[NSMutableString alloc] initWithString:str];
int count = (int)str1.length;
for (int i = 0; i <= (count/2); i++)
{
char left = [str1 characterAtIndex:i];
char right = [str1 characterAtIndex:(count - i - 1)];
NSString *rightnow = [[NSString alloc]initWithFormat:@"%c",left];
NSString *leftnow = [[NSString alloc]initWithFormat:@"%c",right];
[str1 replaceCharactersInRange:NSMakeRange(i, 1) withString:leftnow];
[str1 replaceCharactersInRange:NSMakeRange((count - i - 1), 1) withString:rightnow];
}
return str1;
}
@end
//
// NSString+Countzimu.h
//
// 计算英文字母的个数(比如@”5435abc54abc3AHJ5”调用方法后返回的是9)
#import <Foundation/Foundation.h>
@interface NSString (Countzimu)
+ (int)docountzimu:(NSString *)str;
@end
//
// NSString+Countzimu.m
//
#import "NSString+Countzimu.h"
@implementation NSString (Countzimu)
+ (int)docountzimu:(NSString *)str
{
int num = 0;
for (int i = 0; i < str.length; i++)
{
if ((([str characterAtIndex:i] >= 'a') && ([str characterAtIndex:i] <= 'z')) || (([str characterAtIndex:i] >= 'A') && ([str characterAtIndex:i] <= 'Z')))
{
num++;
}
}
return num;
}
@end
//
// NSString+Delspace.h
//
// 去除字符串两端空格(比如@” 1235 45 ”调用方法后返回@”1235 45”)
#import <Foundation/Foundation.h>
@interface NSString (Delspace)
+ (NSString *)dodelspace:(NSString *)str;
@end
//
// NSString+Delspace.m
//
#import "NSString+Delspace.h"
@implementation NSString (Delspace)
+ (NSString *)dodelspace:(NSString *)str
{
NSMutableString *str1 = [[NSMutableString alloc] initWithString:str];
while ([str1 characterAtIndex:0] == ' ')
{
[str1 deleteCharactersInRange:NSMakeRange(0, 1)];
}
while ([str1 characterAtIndex:([str1 length] - 1)] == ' ')
{
[str1 deleteCharactersInRange:NSMakeRange(([str1 length] - 1), 1)];
}
return str1;
}
@end
//
// main.m
//
#import <Foundation/Foundation.h>
#import "NSString+Delspace.h"
#import "NSString+Turnback.h"
#import "NSString+Countzimu.h"
int main()
{
NSString *str = @" ujdu ";
NSLog(@"\n%@",[NSString dodelspace:str]);
NSString *str1 = @"1234567890abcdefghijklmn";
NSLog(@"\n%@",[NSString doturnback:str1]);
NSString *str2 = @"122819427jhjhjhjh";
NSLog(@"\n%d",[NSString docountzimu:str2]);
return 0;
}