免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3483 | 回复: 3
上一主题 下一主题

[C++] 字符串与常规char数组的区别 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-08-20 09:57 |只看该作者 |倒序浏览
C++ Primer Plus第6版中文版 程序清单7.9 strgfun.cpp

  ----书上有这么一段话:“ 但字符串与常规char数组只是数组之间的一个重要区别是,字符串有内置的结束字符,而char数组只是数组不是字符串。这意味着不用将字符串的长度作为参数传递给函数,而函数可以使用循环依次检查字符串中的每个字符,直到遇到结尾的空值字符为止。”
然后附了下面这段例子,但我没的看出有什么区别,求教!!


  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;

  4. unsigned int c_in_str(const char * str, char ch);

  5. int _tmain(int argc, _TCHAR* argv[])
  6. {

  7.     char mmm[15] = "minimum";    // string in an array
  8. // some systems require preceding char with static to
  9. // enable array initialization

  10.     char *wail = "ululate";    // wail points to string

  11.     unsigned int ms = c_in_str(mmm, 'm');
  12.     unsigned int us = c_in_str(wail, 'u');
  13.     cout << ms << " m characters in " << mmm << endl;
  14.     cout << us << " u characters in " << wail << endl;
  15.     cin.get();
  16.     return 0;
  17. }

  18. // this function counts the number of ch characters
  19. // in the string str
  20. unsigned int c_in_str(const char * str, char ch)
  21. {
  22.     unsigned int count = 0;

  23.     while (*str)        // quit when *str is '\0'
  24.     {
  25.         if (*str == ch)
  26.             count++;
  27.         str++;        // move pointer to next char
  28.                 cout <<*str<<endl;
  29.     }
  30.        
  31.     return count;
  32. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2014-08-20 16:06 |只看该作者
#include<stdio.h>
int main(int argc,char *argv[])
{
        char *a = "wkj";
        char b[3] = "wkj";
        xunhuan(a);
        xunhuan(b);
        return 0;

}
int xunhuan(char *a)
{
        int count = 0;
        while(*a)
        {count++;a++;}
        printf("%d\n",count);

}

输出:
3
11

论坛徽章:
0
3 [报告]
发表于 2014-08-20 16:07 |只看该作者
你把数组这样赋值就能看出区别了
  1. char mmm[15];
  2. mmm[0]='m';
  3. mmm[1]='i';
  4. mmm[2]='n';
  5. mmm[3]='i';
  6. mmm[4]='m';
  7. mmm[5]='u';
  8. mmm[6]='m';
复制代码

论坛徽章:
0
4
发表于 2014-08-20 17:31
亚帝文Senior Software Engineer

-        Must have 5+ years of working experience in VC++ developing.
-        Must have 3+ years of working experience in MFC.
-        Must have experience in module design.
-        Must have experience in SQL Server.

2634161279@qq.com
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP