C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  117 Posts :: 2 Stories :: 61 Comments :: 0 Trackbacks

常用链接

留言簿(8)

搜索

  •  

最新评论

阅读排行榜

评论排行榜


第一个程序:
      C-styel string与常规char数组之间的一个重要区别是,字符串有内置的结束字符(前面讲过,包含字符,但不以空值,而不是字符串)。这意味着不必将字符串长度作为参数传递给函数,而函数可以使用循环依次检查字符串中的每个字符,直到遇到结尾的空值字符为止。下面演示这种方法,使用一个函数来计算特定的字符在字符串中出现的次数。
#include "stdafx.h"
#include 
<iostream>
using namespace std;
int c_in_str(const char * str,char ch);
int main(int argc, char* argv[])
{
    
char mmm[15]="minimum";    //string in an array
  
// some system require preceding char with static to 
  
// enable array initialization
    char *wail="ululate";    //wail points to string

    
int ms=c_in_str(mmm,'m');
    
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
//c_in_str()函数不应修改原始字符串,因此它在声明形参str时使用了限定符const
//这样,如果错误地址函数修改了字符串的内容,编译器将捕获这种错误。
int c_in_str(const char * str, char ch)
{
    
int count=0;
    
while(*str)    //quit when *str is '\0'
    {
        
if(*str==ch)
            count
++;
        str
++;    //move pointer to next char
    }

    
return count;
}

第二个程序:返回C-style string的函数
      函数无法返回一个字符串,但可以返回字符串的地址,这样做的效率更高。下面程序定义了一个名为buildstr()的函数,该函数返回一个指针。该函数接受两个参数:一个字符和一个数字。函数使用new创建一个长度与数字参数相等的字符串,然后将每个元素都初始化为该字符。然后,返回指向新字符串的指针。   
#include "stdafx.h"
#include 
<iostream>
using namespace std;
char * buildstr(char c, int n);    //prototype
int main(int argc, char* argv[])
{
    
int times;
    
char ch;

    cout
<<"Enter a character: ";
    cin
>>ch;
    cout
<<"Enter an integer: ";
    cin
>>times;
    
char * ps =buildstr(ch, times);
    cout
<<ps<<endl;
    delete [] ps;    
//free memory
    ps=buildstr('+',20);//reuse pointer
    cout<<ps<<"-DONE-"<<ps<<endl;
    delete[] ps;
    
return 0;
}

char * buildstr(char c,int n)
{
    
char * pstr =new char[n+1];
    pstr[n]
='\0';
    
//之所以从后向前(而不是从前向后)填充字符串,是为了避免使用额外的变量。
    while((n--)>0)
        pstr[n]
=c;    //fill test of string
    return pstr;
}
posted on 2010-02-12 17:47 烟皑 阅读(572) 评论(0)  编辑 收藏 引用 所属分类: C++ primer plus学习笔记

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理