C++:char数组和string类

参考文章:https://www.runoob.com/cplusplus/cpp-strings.html

概述

C++ 提供了以下两种类型的字符串表示形式:
C 风格字符串
C++ 引入的 string 类类型

C 风格字符串

定义

C 风格的字符串起源于 C 语言,并在 C++ 中继续得到支持。字符串实际上是使用 null 字符 '' 终止的一维字符数组。因此,一个以 null 结尾的字符串,包含了组成字符串的字符。

下面的声明和初始化创建了一个 "Hello" 字符串。由于在数组的末尾存储了空字符,所以字符数组的大小比单词 "Hello" 的字符数多一个。

char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};

依据数组初始化规则,您可以把上面的语句写成以下语句:

char greeting[] = "Hello";

字符串操作函数

C++:char数组和string类

代码示例

#include "stdafx.h"
#include "stdlib.h"
#include <string>
#pragma warning( disable : 4996) 
#include <iostream>

using namespace std;

int main()
{
    char str1[11] = "Hello";
    char str2[11] = "World";
    char str3[11];
    int  len;

    // 复制 str1 到 str3
    strcpy(str3, str1);
    cout << "strcpy( str3, str1) : " << str3 << endl;  // Hello

    // 连接 str1 和 str2
    strcat(str1, str2);
    cout << "strcat( str1, str2): " << str1 << endl;   // HelloWorld

    // 连接后,str1 的总长度
    len = strlen(str1);
    cout << "strlen(str1) : " << len << endl;    // 10
    system("pause");
    return 0;
}

C++ 风格字符串

C++ 标准库提供了 string 类类型,支持上述所有的操作,另外还增加了其他更多的功能。

基本操作

字符串复制:“=”
字符串拼接:“+”

代码示例

#include "stdafx.h"
#include "stdlib.h"
#include <string>
#pragma warning( disable : 4996) 
#include <iostream>

using namespace std;

int main()
{
    string str1 = "Hello";
    string str2 = "World";
    string str3;
    int  len;

    // 复制 str1 到 str3
    str3 = str1;
    cout << "str3 : " << str3 << endl;

    // 连接 str1 和 str2
    str3 = str1 + str2;
    cout << "str1 + str2 : " << str3 << endl;

    // 连接后,str3 的总长度
    len = str3.size();
    cout << "str3.size() :  " << len << endl;
    system("pause");
    return 0;
}

获得字符串的长度

对于char数组,可以使用sizeof()和strlen()函数;对于string类,可以使用str.size()和str.length()函数

#include "stdafx.h"
#include "stdlib.h"
#include <string>
#pragma warning( disable : 4996) 
using namespace std;

int main()
{
    int size;
    const char* str1 = "0123456789";
    const char str2[] = "0123456789";
    string str3 = "0123456789";

    size = sizeof(str1);
    printf("str1 的长度为:%dn", size);  // 打印指针的长度  4
    size = sizeof(str2);
    printf("str2 的长度为:%dn", size); // 打印字符数组的长度,包括字符串结束字符"/0"   11
    size = strlen(str2);
    printf("str2 的长度为:%dn", size); // 打印字符数组的长度,不包括字符串结束字符   10

    size = str3.length();
    printf("str3 的长度为:%dn", size); // 打印字符串的长度,不包括字符串结束字符   10
    size = str3.size();
    printf("str3 的长度为:%dn", size); // 打印字符串的长度,不包括字符串结束字符   10

    system("pause");
        return 0;
}

原文链接: https://www.cnblogs.com/wt-seu/p/12831259.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++:char数组和string类

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/346403

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午3:52
下一篇 2023年3月2日 上午3:53

相关推荐