/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:呼亚萍
* 完成日期:2014年 12 月 14日
* 版 本 号:v1.0
*
* 问题描述:用指针作做参数,求str的长度并返回
* 输入描述:相应的程序
* 程序输出:str的长度
*/
#include <iostream>
using namespace std;
int pstrlen(char *str);
int main()
{
char s1[50]="Hello world. ";
char s2[50]="Good morning. ";
char s3[50]="Hu yaping. ";
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
cout<<"字符串的长度为:"<< pstrlen(s1)<<endl;
cout<<"字符串的长度为:"<< pstrlen(s2)<<endl;
cout<<"字符串的长度为:"<< pstrlen(s3)<<endl; //返回值为char*型,可以直接显示
return 0;
}
//作为示例,本函数采用了形参为数组,在实现中,直接用下标法进行访问
//实际上,在实现中,完全可以用指针法访问
int pstrlen(char *str)
{
int i=0,j=0;
while(*(str+i)!='\0')
{
++i;
++j;
}
return j;
}
运算结果:
知识点总结;
在字符串不是空格时计算其字母的个数,其无法用数组串中的i,便引入新变量j,计算字符串的长度
学习心得:
孰能生巧,多加练习,加油!