C++基础整理 —— C串 & 字符串(1)

  • C-串:

    • 操作c串的库函数:比如拼接 strcpy(s1, s2);
    • C-串首地址:为字符数组的数组名,比如01001000;
    • 长度:字符串长度+1strlen(buffe)=7;
    • char buffer[7]=“Hello!”;
  • string串:

    • 长度: a.length(); //输出本身长度; a.substr(0,2);//返回从第0个位置开始后2个字符; c=atoi(a.c_str()) ; //字符串到整型的转换
    • string a="123"; // 空间占用:需要多少,用多少
#include "iostream"
#include "cstring"
#include <stdlib.h>
#include "string"
using namespace std;

int main()
{
    // C 串
    char a[10]="abcd";
    char b[5]="efgh";
    cout<<strlen(a)<<endl;                     // 数组a的有效长度:4
    cout<<strlen(b)<<endl;                     // 4
    cout<<sizeof(a[0])<<endl;                  // 1
    cout<<sizeof(a)/sizeof(a[0])<<endl;        // 10
    strcat(a,b);
    cout<<"len(a+b):"<<strlen(a)<<endl;        // 连接后数组a的有效长度:8
    cout<<sizeof(a)/sizeof(a[0])<<endl;        // 10
    // cout<<std::end(a)-std::begin(a)<<endl;  //不成功
    for (int i=0;a[i]!='\0';i++)
        cout<<a[i];                            // abcdefgh
    cout<<""<<endl;

    // string 串
    string c="123";
    cout<<c.length()<<endl;         // 3
    cout<<c.substr(0,2)<<endl;      // 返回从第0个位置开始后2个字符:12
    cout<<atoi(c.c_str())<<endl;    // 字符串转换为整型:转换为c的字符串形式,然后用atoi完成转换:123
    return 0;
}

结果:

注:
   strlen  不把\0计入字符串的长度的;头文件在C中用 #include "string",在C++中用 #include "cstring"
   sizeof  计算的则是分配的数组所占的内存空间的大小
   atoi    头文件需要 #include <stdlib.h>

猜你喜欢

转载自blog.csdn.net/kongli524/article/details/88188971