c 风格字符串总结

开始转载之前,我先补充两点
a str  strn 类函数 是c语言风格的操作,所以在里面用到的必须位字符串面值
b “+”这个操作符号,左右两边必须一个要为string,否则将报错。这是因为 + 操作符在重写的时候,要求的是string类型,如果两个都是字符串常量则无法转换为string类型了 
    eg
              string s1 = "hello";
              string s2 = "world";
              string s3 = s1+"world"; // ok
              string s4 = "hello"+"world"; //error
c 使用str strn 类型函数时,一定要注意字符串长度是否足够,且一定要特别注意 strlen 计算时是不包括“null”的,所以要记得+1

在这里我在附上 字符串字面值的函数操作:  http://see.xidian.edu.cn/cpp/u/hs2/
                                                                                     http://wenku.baidu.com/view/9521201cc281e53a5802ff77.html

1.字符串字面值
     字符串字面值是一串常量字符,字符串字面值常量用双引号括起来的零个或多个字符表示,为兼容C语言,C++中所有的字符串字面值都由编译器自动在末尾添加一个空字符
    "Hello World!"  //simple string literal
        ""              //empty string literal
     "\nCC\toptions\tfile.[cC]\n"   //string literal using newlines and tabs

    字符字面值: 'A'   //single quoto:character literal
    字符串字面值: "A"   //double quote:character string literal.包含字母A和空字符的字符串

2.C风格字符串
        事实上C中是没有定义字符串的,所谓的字符串只是末尾加了空字符('\0')的字符数组。字符串字面值的类型实质是const char类型的数组。C++从C语言继承下来的一种通用结构是C风格字符串,而字符串字面值就是该类型的实例。C风格字符串是以空字符null结束的字符数组:
      char ca1[]={'C', '+', '+'};          // 没有空字符null,不是C风格字符串
      char ca2[]={'C', '+', '+', '\0'};    // C风格字符串定义方法1 
      char ca3[]="C++";        // C风格字符串定义方法2,编译器自动在最后加空字符
      const char *cp="C++";    // C风格字符串定义方法3,编译器自动在最后加空字符
      char *cp1=ca1;       // points to first element of a array, but not C-style strin   字符指针,它指向的不是字符串,而是字符数组
      char *cp2=ca2;       // points to first element of a null-terminated char array   字符指针,它指向的是C风格的字符串
      ca1和cp1都不是C风格字符串:ca1是一个不带结束符null的字符数组,而指针cp1指向ca1,因此,它指向的并不是以null结束的数组。

2.1 C风格字符串的使用
       C++语言通过(const) char *类型的指针来操纵C风格字符串。
       const char *cp = "some value";   // 一个C风格字符串
       while(*cp)  //判断cp当前指向的字符是true还是false,true表明这是除null外的任意字符
       {
             // do something to *cp
            ++cp;
       }
2.2 C风格字符串的标准库函数
       #include <cstring>   // cstring是string.h头文件中的C++版本,而string.h是C语言提供的标准库
       操纵C风格字符串的标准库函数:
       strlen(s)            // 返回s的长度,不包括字符串结束符null
       strcmp(s1, s2)
       strcat(s1, s2)       // 将字符串s2连接到s1后,并返回s1 
       strcpy(s1, s2)       // 将s2复制给s1,并返回s1
       strncat(s1, s2, n)   // 将s2的前n个字符连接到s1后面,并返回s1
       strncpy(s1, s2, n)   // 将s2的前n个字符复制给s1,并返回s1
       if(cp1 < cp2)    // compares address, not the values pointed to
       const char *cp1 = "A string example";
       const char *cp2 = "A different string";
       int i=strcmp(cp1, cp2);    // i is positive
       i=strcmp(cp2, cp1);        // i is negative
       i=strcmp(cp1, cp1);        // i is zero
   2.3 永远不要忘记字符串结束符null
       char ca[]={'C', '+', '+'};   // not null-terminated
       cout << strlen(ca) << endl;  // disaster: ca isn't null-terminated
   2.4 调用者必须确保目标字符串具有足够的大小
        // Dangerous:What happens if we miscalculate the size of largeStr?
       char largeStr[16+18+2];   // will hold cp1 a space and cp2
       strcpy(largeStr, cp1);    // copies cp1 into largeStr
       strcat(largeStr, " ");    // adds a space at end of largeStr
       strcat(largeStr, cp2);    // concatenates cp2 to largeStr
        // prints A string example A different string
       cout << largeStr << endl;
   2.5 使用strn函数处理C风格字符串
       char largeStr[16+18+2]    // to hold cp1 a space and cp2
       strncpy(largeStr, cp1, 17);   // size to copy includes the null
       strncat(largeStr, " ", 2);    // pedantic, but a good habit
       strncat(largeStr, cp2, 19);   // adds at most 18 characters, plus a null
   2.6 尽可能使用标准库类型string
       string largeStr = cp1;    // initialize largeStr as a copy of cp1
       largeStr += " ";    // add space at end of largeStr
       largeStr += cp2;    // concatenate cp2 onto end of largeStr
       此时,标准库负责处理所有的内在管理问题。
/
 C风格字符串和C++风格字符串的区别呢?

C风格字符串:对字符串进行操作的 C 函数定义在头文件<cstring>中;

     1. 字符串定义:char* result;

     2. 字符串的最后一个字符是null字符('\0'),可以通过这个字符确定字符串的结尾。

     3. strlen()返回的是字符串的大小;因此,分配空间的时候,需要比字符串的实际空间大1.

     e.g. char* copyString(const char* inString)

          {

             char *result = new char[strlen(inString)];//BUG! off by one

             strcpy(result, inString);

             return result;

           }

      explain: strlen()返回的是字符串的大小,比如"ab",返回的是2。而在new进行分配的时候,需要为'\0'分配一个空间。分配语句要写作,char *result = new char[strlen(inString) + 1];

    4. strcpy(a,b):将字符串b的内容赋值给字符串a;a的大小可以大于b,将b放在a的开始的位置;

      strcat(a,b):将字符串b拼接到字符串a的现有字符后面;

C++风格字符串:使用C++风格字符串的时候,要将它当做是一个普通的类型,如int,这样反而会避免将string作为一个类来理解所带来的很多问题。

     1. 支持<cstring>中许多函数完成的同样操作。

     2. 字符串定义:string myString = “hello”;

     3. 操作符 = :复制字符串;比如,string newone = original;会将后者复制给前者,不会出现两个变量同样指向一个内存的情况。

     4. 可以像int一样使用 == 之类的操作符

     5. 可以改变字符串中的某一个字符。 如 string myString = "hello"; mystring[0] = 'l'; 这中操作是允许的。

字符串直接量:字符串没有变量名字,自身表示自身。

    1. string literal:字符串直接量: e.g. cout<<"hello"<<endl; 代码中通过包含"hello"字符串自身来将其输出,并未包含该字符串的变量。

    2. 字符串直接量可以赋值给变量,但是与字符串直接量相关联的内存空间位于只读部分,因此它是常量字符数组。

        char* ptr = "hello";

        ptr[1] = 'a';//crash! attemps to write to read-only memory.

    因此,当引用字符串直接量的时候使用指向const的字符数组:

       const char* ptr = "hello";

       ptr[1] = 'a';//bug! attempts to write to read-only memory.

    3. 当将字符串直接量赋值给字符数组的初始值的时候。由于字符数组存放与栈中,不允许引用其他地方的内存,因此编译器会将字符串直接量复制到站的数组内存中。因此,可以进行相应的修改。

      char  stackArray[] = "hello";

      stackArray[1] = 'a';

//

那么如何将C风格字符串和string对象进行相互转换呢?

C++中有专门用来处理字符串的类string,其中有众多字符串操作函数以及重载的字符串运算操作符。例如string::bool empty(), = += + == 等。
C语言中的利用字符数组来构成字符串,字符串操作主要靠库函数,例如strcmp strcpy 等等。

在两种字符串混合使用时应注意:

1.C++中的string类同C语言中的字符数字混合计算时,C语言中的字符数组默认被转换成string类对象后,在进行运算。所以可以以下的表达式是合法的:
example1
const char *pc = ", ";
string s1( "hello" );
string s2( "world" );
string s3 = s1 + pc + s2 + "\n";

example2
string s1;
const char *pc = "a character array";
s1 = pc; // ok

2.反向的转换不能自动执行对隐式地将string 对象转换成C 风格的字符串,string类型没有提供支持。例如下面试图用s1 初始化str 就会在编译时刻失败
char *str = s1; // 编译时刻类型错误
为实现这种转换必须显式地调用名为c_str()的操作
char *str = s1.c_str(); // 几乎是正确的但是还差一点

名字c_str()代表了string 类型与C 风格字符串两种表示法之间的关系字面意思是,给我一个C 风格的字符串表示——即指向字符数组起始处的字符指针,但是这个初始化还是失败了,这次是由于另外一个不同的原因为了防止字符数组被程序直接处理,c_str()返回了一个指向常量数组的指针。
const char*str 被定义为非常量指针所以这个赋值被标记为类型违例正确的初始化如下:
const char *str = s1.c_str(); // ok

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值