码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 字符串

时间:2014-09-02 17:18:14      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   ar   2014   

C++ Primer Plus 第6版

字符串:是存储在内存的连续字节中的一系列字符


 

C++处理字符串的方式有2种:

一、来自C语言、常被称为C-风格字符串(C-Style-string)

  1)从字符数组--》字符串

  存储在连续字节中的一系列字符意味着可以讲字符串存储在char数组中,其中每个字符都位于自己的数组元素中。

  C-style字符串具有一种特殊的性质:以空字符结尾,空字符被写为‘\0‘

char dog[8]={b,e,a,u,t, ,i,i};   //不是一个字符串,仅仅是一个char数组!!!
char cat[8]={b,e,a,u,t,a,i,\0};  //是一个字符串,且为一个char数组

  将字符数组初始化为字符串的方法(这种字符串被称为字符串常量字符串字面值):

char bird[11]="Mr.  Cheeps";
char fish="Bubbles";

  用双引号括起的字符串隐式地包括空字符(‘\0‘),因此不用显示的包括它。

  2)从字符串--》字符数组

  将字符串读入到char数组中,将自动加上结尾的空字符(‘\0‘)

  bubuko.com,布布扣

  3)字符串常量与字符常量不能互换

  字符常量(‘S’)是字符串编码的简写表示,在ASCII系统上,‘S’是83的另一种写法,因此下面是将83赋值给shirt_size;

char  shirt_size=s;

  "S"不是字符常量,它表示的是俩个字符(字符S和\0)组成的字符串。

  “S”实际上表示的是字符串所在的内存地址。

char  shirt_size="s"; //将一个内存地址给   shirt_size

  4)注意cout 当读取到‘\0‘就结束继续读取,直接结束

#include <iostream>        
#include <cstring>
int main()
{
   using namespace std;
    int a;
    const int Size=15;
    char name1[Size];             //empty array
    char name2[Size]="C++owboy"; //initialized array
    cout<<"Howdy! i‘m "<<name2;
    cout<<"I what‘s your name?\n";
    cin>>name1;
    cout<<"Well, "<<name1<<" , you name has";
    cout<<strlen(name1)<<"letters and is stored\n";
    cout<<"in an array of "<<sizeof(name1)<<" bytes. \n";
    cout<<"you inital is "<<name1[0]<<".\n";
    name2[3]=\0;
    cout<<"Here are the first 3 characters of my name :"<<name2<<endl;
    cin>>a;
    return 0;    
}

bubuko.com,布布扣

bubuko.com,布布扣

二、string类库的方法

 

C++ 字符串

标签:style   blog   http   color   os   io   strong   ar   2014   

原文地址:http://www.cnblogs.com/holyson/p/3951839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!