1 OC中把字符串倒叙,且每个单词正序, 并计算单词数,两个单词间空格多少不影响结果@”hello world how are you”,
代码如下
.m
@interface ViewController ()
@property (nonatomic , strong )NSString *demo ;//单个单词
@property (nonatomic , strong )NSString *resutStr;
@end
@implementation ViewController
//懒加载
-(NSString *)resutStr{
if (_resutStr == nil) {
_resutStr = [NSString string];
}
return _resutStr;
}
-(NSString *)demo{
if (_demo == nil) {
_demo = [NSString string];
}
return _demo;
}
- (void)viewDidLoad {
[super viewDidLoad];
int n = 1 ; //总单词数
NSString *strs = @"hello world how are you";
NSLog(@"%@",strs);
strs = [strs stringByAppendingString:@" "];//长度加1
for (NSInteger i = strs.length - 1 ; i >= 0 ; i--) {
NSRange range = NSMakeRange(i, 1);
NSString *str = [strs substringWithRange:range];
//将几个字母组成的单词倒叙(两次倒叙为正)
if ([str isEqual: @" "]) {
for (NSInteger m = self.demo.length - 1 ; m >= 0; m--) {
NSRange rangeDemo = NSMakeRange(m, 1);
NSString *strDemo = [self.demo substringWithRange:rangeDemo];
// NSLog(@"%@", strDemo);
//记录输出
self.resutStr = [self.resutStr stringByAppendingString:strDemo];
}
//只有同时满足下列两个条件才是一个单词
if ( (![self.demo isEqual:@" "]) && (![self.demo isEqual:@""]) ) {
n = n +1 ;
}
self.demo = nil;
}
//将几个字母组成单词,
self.demo = [self.demo stringByAppendingString:str];
}
//第一个单词不会打印, 另外打印
for (NSInteger m = self.demo.length - 1 ; m >= 0; m--) {
NSRange rangeDemo = NSMakeRange(m, 1);
NSString *strDemo = [self.demo substringWithRange:rangeDemo];
if (![strDemo isEqual:@" "]) {
// NSLog(@"%@", strDemo);
self.resutStr = [self.resutStr stringByAppendingString:strDemo];
}
}
NSLog(@"%@\n 总单词数%d",self.resutStr,n);
}
@end