Chinaunix首页 | 论坛 | 博客
  • 博客访问: 201843
  • 博文数量: 63
  • 博客积分: 2764
  • 博客等级: 少校
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-28 21:11
文章分类

全部博文(63)

文章存档

2011年(35)

2010年(28)

我的朋友

分类: C/C++

2010-12-22 12:24:31

3.2.4. string 对象中字符的处理
我们经常要对 string 对象中的单个字符进行处理,例如,通常需要知道某
个特殊字符是否为空白字符、字母或数字。表 3.3 列出了各种字符操作函数,
适用于 string 对象的字符(或其他任何 char 值)。这些函数都在 cctype 头
文件中定义。
表 3.3. cctype 中的函数
isalnum(c) 如果 c 是字母或数字,则为 True。
isalpha(c) 如果 c 是字母,则为 true。
iscntrl(c) 如果 c 是控制字符,则为 true
isdigit(c) 如果 c 是数字,则为 true。
isgraph(c) 如果 c 不是空格,但可打印,则为 true。
islower(c) 如果 c 是小写字母,则为 true。
isprint(c) 如果 c 是可打印的字符,则为 true。
ispunct(c) 如果 c 是标点符号,则 true。
isspace(c) 如果 c 是空白字符,则为 true。
isupper(c) 如果 c 是大写字母,则 true。
isxdigit(c) 如果是 c 十六进制数,则为 true。
tolower(c) 如果 c 大写字母,返回其小写字母形式,否则直接返回 c。
toupper(c) 如果 c 是小写字母,则返回其大写字母形式,否则直接返回 c。
125
表中的大部分函数是测试一个给定的字符是否符合条件,并返回一
个 int 作为真值。
如果测试失败,
则该函数返回 0 ,
否则返回一个
(无意义的)
非 0 ,表示被测字符符合条件。
表中的这些函数,可打印的字符是指那些可以表示的字符,空白字符则是空
格、制表符、垂直制表符、回车符、换行符和进纸符中的任意一种;标点符号则
是除了数字、字母或(可打印的)空白字符(如空格)以外的其他可打印字符。
这里给出一个例子,运用这些函数输出一给定 string 对象中标点符号的个
数:
string s("Hello World!!!");
string::size_type punct_cnt = 0;
// count number of punctuation characters in s
for (string::size_type index = 0; index != s.size(); ++index)
if (ispunct(s[index]))
++punct_cnt;
cout << punct_cnt
<< " punctuation characters in " << s << endl;
这个程序的输出结果是:
3 punctuation characters in Hello World!!!
和返回真值的函数不同的是,tolower 和 toupper 函数返回的是字符,返
回实参字符本身或返回该字符相应的大小写字符。我们可以用 tolower 函数
把 string 对象 s 中的字母改为小写字母,程序如下:
// convert s to lowercase
for (string::size_type index = 0; index != s.size(); ++index)
s[index] = tolower(s[index]);
cout << s << endl;
得到的结果为:
hello world!!!

阅读(2673) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~