黑马程序员技术交流社区
标题:
入学测试题5
[打印本页]
作者:
泥娃娃
时间:
2016-3-19 14:08
标题:
入学测试题5
main.m
#import <Foundation/Foundation.h>
//分别引入扩展的三个方法的头文件
#import "NSString+reverse.h"
#import "NSString+CountNum.h"
#import "NSString+deleteWhiteSpace.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 1. 字符串反串
//定义一个可变字符串string
NSMutableString *string = [NSMutableString stringWithFormat:@"123"];
//调用Reverse,生成新字符串
NSString *str = [NSString stringWithString:[string Reverse]];
NSLog(@"%@",str);//输出
// 2. 计算英文字母个数
NSString *str1 = @"5435abc54abc3AHJ5";//定义一个字符串str1
NSUInteger d =[str1 CountNum];//调用CountNum
NSLog(@"%ld",d);//输出
// 3. 去掉字符串首尾空格
NSString *str2 = @" 1235 45 ";//定义一个字符串str2
NSString *str3 =[str2 deleteWhiteSpace];//调用deleteWhiteSpace
NSLog(@"%@",str3);//输出
}
return 0;
}
复制代码
1.字符串反转
声明
#import <Foundation/Foundation.h>
@interface NSString (reverse)
//声明Reverse
-(NSMutableString*)Reverse;
@end
复制代码
实现
@implementation NSString (reverse)
//实现Reverse
-(NSMutableString*)Reverse{
NSUInteger length = [self length];//string长度length
// 按照指定长度创建一个数组
NSMutableArray *array = [NSMutableArray arrayWithCapacity:length];
for(long i=length-1; i>=0; i--){//从头到尾反向存入数组中
unichar c = [self characterAtIndex:i];//返回下标对应的字符
//添加到数组
[array addObject:[NSString stringWithFormat:@"%c",c]];
}
NSMutableString *str = [NSMutableString stringWithCapacity:length];
for(int i=0; i<=length-1; i++){
[str appendString:array[i]];//将数组内的字符依次存入字符串中
}
return str;
}
@end
复制代码
2.计算英文字母个数
声明
#import <Foundation/Foundation.h>
@interface NSString (CountNum)
//声明CountNum
-(NSUInteger)CountNum;
@end
复制代码
实现
#import "NSString+CountNum.h"
@implementation NSString (CountNum)
//实现CountNum
-(NSUInteger)CountNum{
NSUInteger length = [self length];//str1长度length
const char *s = [self UTF8String];//str1转化为英文字符再做统计
int CountNum=0;
for (int i=0; i<length; i++) {
// 判断哪些是英文字母 ,如果是,CountNum+1
if ((s[i]>='a'&&s[i]<='z' )|| (s[i]>='A'&&s[i]<='Z')) {
CountNum++;
}
}
return CountNum;
}
@end
复制代码
3.去除字符串两端空格
声明
#import <Foundation/Foundation.h>
@interface NSString (deleteWhiteSpace)
//声明deleteWhiteSpace
-(NSString *)deleteWhiteSpace;
@end
复制代码
实现
#import "NSString+deleteWhiteSpace.h"
@implementation NSString (deleteWhiteSpace)
//实现deleteWhiteSpace
-(NSString *)deleteWhiteSpace{
// 去掉首位空格
NSString *str1 = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return str1;
}
@end
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2