21xrx.com
2024-06-03 04:39:59 Monday
登录
文章检索 我的文章 写文章
C++中如何表示字符串
2023-07-12 12:39:24 深夜i     --     --
C++ 字符串 表示方法 字符数组 指针

在C++中,字符串是一系列字符的集合。表示字符串可以用char类型的数组或者字符串字面值。

用char类型的数组表示字符串时,需要给数组分配足够的空间来存储字符串中的所有字符。例如,下面的代码定义了一个包含5个字符的字符串:


char str[6] = "hello";

需要注意的是,末尾的空字符`\0`也占据了一个位置,因此数组长度要比字符串长度多1。

字符串字面值是一种更方便的表示方法,它们以双引号`"`括起来,C++会自动为其创建一个char类型的数组。例如,下面的代码创建了一个字符串:


const char* str = "hello";

可以使用string类来存储和操作字符串。这是C++标准库中提供的一种字符串类型,它提供了很多便于操作字符串的方法。例如,可以使用string类来实现字符串的拼接、查找子串和分割等操作。


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str1 = "hello";

  string str2 = "world";

  string str3 = str1 + " " + str2; // 拼接字符串

  cout << str3 << endl;

  string str4 = "hello world";

  size_t pos = str4.find("world"); // 查找子串

  if (pos != string::npos)

    cout << "found" << endl;

  

  string str5 = "hello,world,how,are,you";

  size_t start = 0;

  size_t end = str5.find(",");

  while (end != string::npos) {

    string segment = str5.substr(start, end - start); // 分割字符串

    cout << segment << endl;

    start = end + 1;

    end = str5.find(",", start);

  }

  string segment = str5.substr(start); // 处理最后一个分隔符后的子串

  cout << segment << endl;

  return 0;

}

以上示例代码展示了使用string类进行字符串操作的方法,更多关于string类的详细说明可以查阅C++标准库文档。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复