- #import <Foundation/Foundation.h>
- @interface NSString (MJ) // 方法声明
- + (int)letterCount:(NSString *)s1;
- + (NSString *)qukongge:(NSString *)s1;
- @end
- @implementation NSString (MJ) // 方法实现
- // + (int)letterCount:(NSMutableString *)s1
- + (int)letterCount:(NSString *)s1
- {
- int count = 0;
-
- // for (int i = 0 ;i < self.length; i++) 类方法self是类
- for (int i = 0; i < s1.length; i++)
- {
- unichar c = [s1 characterAtIndex:i];
-
- // if(( c >= '65' && c <= '90')||(c >= '97' && c <= '122')) '65'啥也不是。'6' '5' "65" 6 5 65 都不一样
- if(( c >= 65 && c <= 90) || (c >= 97 && c <= 122))
- {
- count++;
- }
- }
- return count;
- }
- + (NSString *)qukongge:(NSString *)s1
- {
- NSMutableString *newS1 = [NSMutableString stringWithString:s1];
-
- // NSMutableString *temp = nil;
-
- // for(int i = 0; i < self.length; i++)
- for(int i = 0; i < newS1.length; i++)
- {
- char c = [newS1 characterAtIndex:i]; // 获取当前位置的字符
-
- if(c == ' ')
- {
- // temp = [newS1 deleteCharactersInRange:NSMakeRange(i, 1)]; 这个方法没有返回值的
- [newS1 deleteCharactersInRange:NSMakeRange(i, 1)];
- --i; // 每次删除字符字符串长度都-1 [newS1 characterAtIndex:i]是相对于新长度的 所以i--;抵消影响
- }
- else
- break;
- }
-
- // for(int k = self.length -1; k >= 0; k--)
- for(int k = (int)newS1.length - 1; k >= 0; k--)
- {
- // char c2 = [newS1 characterAtIndex:i]; // 获取当前位置的字符
- char c2 = [newS1 characterAtIndex:k];
- if(c2 == ' ')
- {
- // temp = [newS1 deleteCharactersInRange:NSMakeRange(k, 1)];
- [newS1 deleteCharactersInRange:NSMakeRange(k, 1)];
- --k;
- }
- else break;
- }
- // return temp;
- return newS1;
- }
- @end
- int main ()
- { // NSMutableString *s1 = @" 12aaabbb35 45 "; 不可变字符串不要这么赋值
- NSString *s1 = @" 12aaabbb35 45 ";
- NSString *s2 = [NSString qukongge:s1];
- int count = [NSString letterCount:s1] ;
- // NSLog(@"去空格后是:%@,字母个数是%@", s2,count);
- NSLog(@"去空格后是:%@,字母个数是:%d", s2, count);
-
- // 用 stringByTrimmingCharactersInSet: 方法删除首尾空格 [NSCharacterSet whitespaceCharacterSet] 表示空格的字符集
- // NSString *s3 = [s1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- // NSLog(@"可以直接去空格:%@", s3);
-
- // 字符串反转(比如@”123”调用方法后返回@”321”)
- NSString *s4 = @"123";
- NSMutableString *str = [NSMutableString string];
- for (int i = (int)s4.length - 1; i >= 0; --i) {
- [str appendFormat:@"%c", [s4 characterAtIndex:i]];
- }
- NSLog(@"%@", str);
- return 0;
- }
复制代码 |