C++之字符串

最近遇到一个C++的项目,准备着手学一些C++的知识。由于本人大部分的C语言知识都已经还给了老师(什么指针的指针...),加上多年以来一直从事java相关的开发,看了一天之后,发现C++这个坑真是大,没有速成,只能一点一点啃。这篇文章就记录一下刚遇到的字符串问题。

开始上代码:

#include <stdio.h>
class Student {
public:
        char *name="javaname...";
        char adrs[5]="test";
        int age=1;
        float score=0.5;
        void say(){
          printf("%s age is: %d,score is:%f\n",name,age,score);
        }
};

int main() {
  class Student stu;
  stu.name="xiao ming";
  str.adrs[0]='a';
  stu.age=2;
  stu.score=98.9;
  stu.say();

  return 0;
}

编译、运行:

[roo@localhost ~]$ g++ abc.cpp 
abc.cpp:4:13: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  char *name="javaname";
             ^
abc.cpp:5:15: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  char adrs[5]="test";
               ^
abc.cpp:6:12: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  int age = 1;
            ^
abc.cpp:7:14: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  float score=0.5;
              ^
abc.cpp:4:13: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  char *name="javaname";
             ^
abc.cpp: In function ‘int main()’:
abc.cpp:15:11: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   stu.name="xiao ming";
           ^

//默认生成a.out可执行文件
[roo@localhost ~]$ ./a.out 
xiao ming age is: 2,score is:98.900002,address:aest

借着这个例子我们总结一下C++中字符串相关知识点。

一、字符数组定义字符串:

C语言中,没有专门的字符串变量,只能将字符串作为字符数组来处理。将一个字符串存放在变量中,必须使用字符数组,即用一个字符型数组来存放一个字符串,数组中每一个元素存放一个字符。

一般我们用字符数组来存放字符串时,都要先确定一个足够大的数组,而实际并用不了那么多,而我们只关心其有效位。为此C规定了一个 '/0' 代表字符串结束标志。系统对字符串常量也自动加一个'/0'作为结束符。

先看一个例子:

#include<iostream>
#include <cstring>

using namespace std;

int main()
{
  char a[10]="hello";
  cout<<sizeof(a)<<endl;//10

  char b[]="hello";
  cout<<sizeof(b)<<endl;//6

  char c[10]={'h','e','l','l','o'};
  cout<<sizeof(c)<<endl;//10

  char d[]={'h','e','l','l','o'};
  cout<<sizeof(d)<<endl;//5

  char e[10];
  strcpy(e,"hello");
  cout<<"strcpy:"<<sizeof(e)<<endl;//10
}

1)字符数组定义字符串三种方式:

  • 定义的时候直接用字符串赋值:char a[10]="hello";和char a[]="hello";是一样的,区别是sizeof大小不一样
  • 对字符数组中字符逐个赋值;char c[10]={'h','e','l','l','o'};
  • 利用strcpy:strcpy(e,"hello");

说明:使用strcpy需要引入#include <cstring>头文件,否则编译会报错,error: ‘strcpy’ was not declared in this scope

:char a[10]="hello";和char a[]="hello";是一样的,但是在class类中对属性赋值时,只能使用前者,否则会报错。例如下面的方式会报错。error: initializer-string for array of chars is too long [-fpermissive]

class Student {
public:
        char *name="javaname...";
        char adrs[]="test";
        int age=1;
        float score=0.5;
        void say(){
          printf("%s age is: %d,score is:%f\n",name,age,score);
        }
};

2)单引号、双引号:

前者是字符,后者是字符串。用单引号引起的一个字符大小就是一个字节。而用双引号引起的字符串大小是字符的总大小+1,因为用双引号引起的字符串会在字符串末尾添加一个二进制为0的字符'\0'。

二、字符指针定义字符串:

char* 是指向字符串的指针(其实严格来说,它是指向字符串的首个字母),你可以让它指向一串常量字符串。使用char*定义字符串,不能改变字符串内的字符的内容,但却可以把另外一个字符串付给它。看下面的例子:

#include<iostream>
using namespace std;
int main()
{
    char str[]="hello world";
    char *p=str;
    cout<<str<<endl;
    cout<<p<<endl;
    cout<<*p<<endl;

    char *str1="java";
    cout<<str1<<endl;
    cout<<*str1<<endl;

    str1="C++";
    cout<<str1<<endl;
}
输出:
hello world
hello world
h
java
j
C++

1、char *str和char str[]区别:

使用char*定义字符串,不能改变字符串内的字符的内容

#include<stdio.h>

int main()
{
  char* str = "hello C++";
  printf("%s\n",str);//hello C++
  str[0]='1';//报错

  char str3[] = "sfdsdfdsfdsfdsfdsf";
  str3[0]='1';
  printf("%s\n",str3);//1fdsdfdsfdsfdsfdsf

  char str4[6] = "12345";
  str4[0]='a';
  printf("%s\n",str4);//a2345
}

:char指针*位置放在哪都可以。例如:char *str、char* str、char * str都一样。

2、内存结构:

接着上面的问题,因为字符指针char *str指向的是字符串常量的地址,那么既然是常量其值必定不能被改写!所以代码中所有的向str[ ]赋值的语句都是非法的!看一个例子:

#include<iostream>
using namespace std;

int main()
{
  char *cards="JQK";
  char a_card=cards[0];
  cout<<a_card<<endl;//J

  cards[2]=cards[1];//报错
  cards[1]='x';//报错
}

  1. 首先编译器将代码中的字符串JQK常量存在内存中的数据段。
  2. 代码定义了一个字符型指针变量cards,所以编译器在栈空间中分配了一个单元给它。
  3. 代码将字符串JQK在数据段中的首地址赋给cards,也就是使cards指向数据段中的字符串JQK。
  4. 代码要求取出字符串中的第二个字符,并将其的值赋给字符串中的第三个字符单元。这里就有问题了,因为字符串所在单元是只读的,无法完成写输入。

所以,当我们将一个字符串常量赋给一个指针时通常要用const关键词来限制,即const char *name = "leon";
 

1)程序内存发配:

一个由c/C++编译的程序占用的内存分为以下几个部分:

  1. 栈区(stack):由编译器自动分配释放,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
  2. 堆区(heap):一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。
  3. 全局区(静态区)(static):全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统释放。
  4. 常量区:常量字符串就是放在这里的。程序结束后由系统释放。
  5. 程序代码区
//main.cpp 

#include <stdio.h>
#include <string.h>
int a=0;    //全局初始化区
char *p1;   //全局未初始化区
main()
{
   int b;栈
   char s[]="abc";   //栈
   char *p2;         //栈
}

2)堆、栈基本知识:

stack:由系统自动分配,如,声明在函数中一个局部变量int b;系统自动在栈中为b开辟空间。
heap:需要程序员自己申请,并指明大小,在c中malloc函数,在C++中用new运算符。如p1=(char*)malloc(10);注意p1本身是在栈中的。

三、string类:

在C++中,char仍然是一个primitive type(原始类型),而string已经经过封装,成为了一个class(类)用到它时,我们需要 #include <string>,它是C++ Standard Library (C++标准库)的一部分。

它包含了对字符串的各种常用操作,它较char*的优势是内容可以动态拓展,以及对字符串操作的方便快捷,用+号进行字符串的连接是最常用的操作。

和字符指针不同,C++中string的定义字符串,能改变字符串内的字符,也可以把另外一个字符串付给它

#include<iostream>

using namespace std;

int main()
{
  string str="hello java";
  cout<<str<<endl;

  str="hello C++";
  cout<<str<<endl;

  str[0]='1';
  cout<<str<<endl;
}
输出:
hello java
hello C++
1ello C++

说明:

1)使用C++中的string,除了头文件外,还需要using namespace std;否则会报,因为,98年以后的c++语言提供一个全局的命名空间namespace,可以避免导致全局命名冲突问题,C++标准库定义了命名空间:std,其中包含容器vector、string等。。。

2)在C++代码中使用了printf("%s",str);类似格式化来处理string类型的时候,出报错:cannot pass object of non-POD type 'string'(aka 'basic_string<char>')through variadic function。原因是printf,scanf,fprinf等可以format的一个字符串中使用"%s"时,只能使用C string;如果是C++ string的话,就必须先变成C string:str.c_str();

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值