当前位置:嗨网首页>书籍在线阅读

16-将C-风格字符串作为参数的函数

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

7.5.1 将C-风格字符串作为参数的函数

假设要将字符串作为参数传递给函数,则表示字符串的方式有3种:

  • char数组;
  • 用引号括起的字符串常量(也称字符串字面值);
  • 被设置为字符串的地址的char指针。

但上述3种选择的类型都是char指针(准确地说是char*),因此可以将其作为字符串处理函数的参数:

char ghost[15] = "galloping";
char * str = "galumphing";
int n1 = strlen(ghost);       // ghost is &ghost[0]
int n2 = strlen(str);         // pointer to char
int n3 = strlen("gamboling"); // address of string

可以说是将字符串作为参数来传递,但实际传递的是字符串第一个字符的地址。这意味着字符串函数原型应将其表示字符串的形参声明为char *类型。

C-风格字符串与常规char数组之间的一个重要区别是,字符串有内置的结束字符(前面讲过,包含字符,但不以空值字符结尾的char数组只是数组,而不是字符串)。这意味着不必将字符串长度作为参数传递给函数,而函数可以使用循环依次检查字符串中的每个字符,直到遇到结尾的空值字符为止。程序清单7.9演示了这种方法,使用一个函数来计算特定的字符在字符串中出现的次数。由于该程序不需要处理负数,因此它将计数变量的类型声明为unsigned int。

程序清单7.9 strgfun.cpp

// strgfun.cpp -- functions with a string argument
#include <iostream>
unsigned int c_in_str(const char * str, char ch);
int main()
{
    using namespace std;
    char mmm[15] = "minimum"; // string in an array
// some systems require preceding char with static to
// enable array initialization
    char *wail = "ululate"; // wail points to string
    unsigned int ms = c_in_str(mmm, 'm');
    unsigned int us = c_in_str(wail, 'u');
    cout << ms << " m characters in " << mmm << endl;
    cout << us << " u characters in " << wail << endl;
    return 0;
}
// this function counts 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 pointer to next char
    }
    return count;
}

下面是该程序的输出:

3 m characters in minimum
2 u characters in ululate

程序说明

由于程序清单7.9中的c_int_str()函数不应修改原始字符串,因此它在声明形参str时使用了限定符const。这样,如果错误地址函数修改了字符串的内容,编译器将捕获这种错误。当然,可以在函数头中使用数组表示法,而不声明str:

unsigned int c_in_str(const char str[], char ch) // also okay

然而,使用指针表示法提醒读者注意,参数不一定必须是数组名,也可以是其他形式的指针。

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

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

str最初指向字符串的第一个字符,因此str表示的是第一个字符。例如,第一次调用该函数后,str的值将为m——“minimum”的第一个字符。只要字符不为空值字符(\0),str就为非零值,因此循环将继续。在每轮循环的结尾处,表达式str++将指针增加一个字节,使之指向字符串中的下一个字符。最终,str将指向结尾的空值字符,使得str等于0——空值字符的数字编码,从而结束循环。