A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Hi围城 中级黑马   /  2014-4-3 16:17  /  1981 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Hi围城 于 2014-4-3 17:20 编辑

字符串中的英文字母咋个判定?比如“bdbga8788dfff“,如何调用方法,实现它的个数判定?

评分

参与人数 1技术分 +1 收起 理由
jing迪 + 1

查看全部评分

4 个回复

倒序浏览
本帖最后由 程浩 于 2014-4-3 17:00 编辑

这是我学习时候写的博客片段,地址:http://blog.csdn.net/kldxcr/article/details/22813973
=======实例2:为系统自带的类添加方法
//1.给NSString增加一个类方法:计算某个字符串中阿拉伯数字的个数
//2.给NSString增加一个对象方法:计算当前字符串中阿拉伯数字的个数
  1. //声明
  2. NSString+Number.h中
  3. #import <Foundation/Foundation.h>
  4. @interface NSString (Number)
  5. + (int)numberCountOfString:(NSString *)str;
  6. - (int) numberCount;//自己调用
  7. @end
  8. //实现
  9. @implementation NSString (Number)
  10. + (int)numberCountOfString:(NSString *)str
  11. {
  12.         int count=0;
  13.         for(int i=0;i<str.length;i++)
  14.         {
  15.                 unichar c=[str characterAtIndex: i];//获取str字符串内部具体某一个字符,NSUIteger就是unsigned long,即数字
  16.                 if(c>='0' && c<='9')//if(c>=48 && c<=57)
  17.                         {
  18.                                 count++;
  19.                         }
  20.         }
  21.         return count;
  22. //========以下代码可以完全代替以上代码========
  23.         return [str numberCount];
  24. }


  25. - (int) numberCount
  26. {
  27.         int count=0;
  28.         for(int i=0;i<self.length;i++)
  29.         {
  30.                 unichar c = [self characterAtIndex:i];//去除i这个位置对应的字符
  31.                 if(c<='9' && c>='0')
  32.                 {
  33.                         count++;
  34.                 }
  35.         }
  36.         return count;
  37. }
  38. @end
  39. //调用
  40. #import <Foundation/Foundation.h>
  41. #import "NSString+Number.h"
  42. init main()
  43. {
  44.         int count1=[NSString numberCountOfString:@"a2134asd"];//类方法可以直接通过NSString 调用类方法
  45.         int count2=[@"123sadf213" numberCount];
  46.         NSlog(@"%d,%d",count1,count2);
  47.         return 0;
  48. }
复制代码



评分

参与人数 1技术分 +1 收起 理由
jing迪 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 于清扬 于 2014-4-3 17:07 编辑
  1. 可以给NSString写个分类,增加个方法

  2. + (NSInteger)letterCountOfString:(NSString *)str
  3. {
  4.     int count = 0;
  5.     // 从字符串的第0个位置开始遍历
  6.     for (int i = 0; i < str.length; i ++) {
  7.         unichar c = [str characterAtIndex:i];
  8.         // 获得字符串中包含数字的个数
  9.         if (c > '0' && c <= '9') {
  10.             count ++;
  11.         }
  12.     }
  13.     // 返回字符串中字母的个数
  14.     return (str.length - count);
  15. }

  16. 列如:
  17. NSString *str = @"ahahdak1287hahdaud212";
  18. [NSString letterCountOfString:str];
复制代码

评分

参与人数 1技术分 +1 收起 理由
jing迪 + 1

查看全部评分

回复 使用道具 举报
程浩 发表于 2014-4-3 16:58
这是我学习时候写的博客片段,地址:http://blog.csdn.net/kldxcr/article/details/22813973[/ ...

谢谢您,我的问题解决了。
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马