c++之string

来源:互联网 发布:linux diff 命令 编辑:程序博客网 时间:2024/06/04 18:04

    今天学习c++的string类型,初次接触,最大的区别就是java的字符串类型String首字母大写,而c++的字符串类型string首字母小写。另外,c++使用string字符串类型之前要引入string:#inclued<string>(就我个人理解:就是类似在java中使用一个类时,需要先import一样)。string也是std函数里面的变量,所以要通过std才能使用string类型

 字符串长度:通过size()方法来得到字符串长度

  写了一个小例子 (提示用户输入姓名,然后通过string变量接受输入的字符串,然后输出姓名)

  

#include  <iostream>
#include <string>
using namespace std;

  main(){
     cout<< "请输入您的名字"<< endl;
     string name ;
     cin>> name;
     cout<< name <<"您好!欢迎使用string" << endl;

    string str(name.size(),'*')//可以使用这种方式创建一个长度和name一样的字符串,并且字符串的每个 字符都是*

  
     system("pause");     
}

 拼接字符串 s+s1

   需要注意,s和s1不能全部是字符串直接量("aaa")和char类型的值

 下面列举些定义字符串的例子

    const std::string hello = "hello";   
   // const std::string str1 = "hello" + "world";//不能通过编译 ,连接的不能是字符串常量
  //  const std::string message = "hello" + ",world"+"!";  //同样的,连接的不能全是字符串常量
    const std::string str2 = hello+"world";//可以通过编译,因为hello是之前定义的变量
    const std::string exclam= "!";  
    const std::string str3 = hello+ "world" +exclam;//可以通过

    const std::string str4 = "hello"+world"+exclam;//不可以通过
    const std::string str5 = hello+"world"+"!" +"oo";//可以通过    const std::string s = "aa"+'s';//可以一个字符串常量和字符常量拼接为字符串
    //const std::string str2 = 'h' + 'e';//连接的不能全是字符常量
 

 关于语句块{}

 {
       const std::string ss = "a string" ;
       std::cout<<ss<<std::endl;
      }
      {
       const std::string ss= "another string"                    ;
       std::cout<<ss<<std::endl;
      }

编译能够通过。ss不会出现命名冲突,说明在语句块里面定义的变量只能在语句块中使用(局部变量)

 {
           const::std::string ss1 = "a string";                                        
           std::cout<<ss1<<std::endl;
           {
              const std::string ss1 = "another string";                         
              std::cout<<ss1<<std::endl;
           }
      }

此种情况还是会通过编译。说明语句块中定义的变量指针对该语句块有效,不会影响该语句块外面的变量

       {
          {
           std::string ss2 = "aaaa";
          }
          std::cout<<ss2<<std::endl;
      }

该情况不能通过编译,因为ss2的作用域只存在里面的语句块,在该语句块外面是不存在该变量的(ss2)。所以编译不能用过