C++PrimerPlus(第6版)中文版:Chapter7.5_strgfun

这段代码展示了如何使用C++编写一个函数`c_in_str()`,该函数接收一个C风格字符串和一个字符,然后计算并返回字符串中指定字符的出现次数。程序在`main()`函数中初始化两个字符串并调用`c_in_str()`,输出含有字符'm'的次数和含有字符'u'的次数。函数利用了while循环遍历字符串,通过比较字符来计数。
// Chapter7.5_strgfun.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
unsigned int c_in_str(const char * str,char ch);

int main()
{
    using namespace std;
    char mmm[15] = "minimum";//string in a arary 
    //some systems require preceding char with static to enable array initialization
     const char  * wail = "ululate"; //wail points to string  //ps:const 原书没有,不加就报错
     unsigned int ms = c_in_str(mmm,'m');
     unsigned int us = c_in_str(wail,'u');
     cout << ms << "m character in" << mmm << endl;
     cout << us << "u character in" << wail << endl;
     return 0;   
}
//this count the number of ch characters in the string str
unsigned int c_in_str(const char* str, char ch)
{
    unsigned int count = 0;
    while (*str)//quit when *str is '\0'
    {
        if (*str == ch)
            count++;
        str++;//move the pointer to next char 
    }
    return count;
}

 本段程序代码主要演示了:将C风格字符串作为参数的函数,实现了计算给定字符串中含有某个字符的数量的功能。

函数c_in_str()不应该修改原始字符串,因此它在声明形参str时使用了限定符const。这样如果错误地使函数修改了字符串的内容,编译器将捕获这种错误。

//this count the number of ch characters in the string str
unsigned int c_in_str(const char* str, char ch)
{
    unsigned int count = 0;
    while (*str)//quit when *str is '\0'
    {
        if (*str == ch)
            count++;
        str++;//move the pointer to next char 
    }
    return count;
}

该函数本身演示了处理字符串中字符的标准方式:

while(*str)
{
   statements;
   str++;
}

        str 最初指向字符串的第一个字符,因此*str表示的是第一个字符。只要字符不为空值字符(\0),*str就为非零值,因此循环将继续。在每个循环的结尾处,表达式str++将指针增加一个字节,使之指向了字符串中的下一个字符。最终str将指向结尾的空值字符,使得*str等于0----空值字符的数字编码,从而结束了循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值