Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++string头文件

作者:携剑笑红尘   发布日期:2025-05-18   浏览:92

#include <iostream>
#include <string> // 引入C++标准库中的string类

int main() {
    // 创建一个字符串对象
    std::string greeting = "Hello, World!";

    // 输出字符串内容
    std::cout << greeting << std::endl;

    // 使用string类的成员函数
    std::string name = "Alice";
    std::string message = "Welcome ";
    message += name; // 拼接字符串
    message.append(" to the C++ world!"); // 使用append方法拼接字符串

    // 输出拼接后的字符串
    std::cout << message << std::endl;

    // 使用find方法查找子串的位置
    size_t pos = message.find("C++");
    if (pos != std::string::npos) {
        std::cout << "Found 'C++' at position: " << pos << std::endl;
    } else {
        std::cout << "'C++' not found" << std::endl;
    }

    return 0;
}

解释说明:

  1. 包含头文件#include <string> 引入了C++标准库中的string类,使得我们可以使用std::string类型。
  2. 创建字符串对象std::string greeting = "Hello, World!"; 创建了一个名为greeting的字符串对象,并初始化为"Hello, World!"。
  3. 输出字符串:使用std::cout将字符串内容输出到控制台。
  4. 字符串拼接:使用+=操作符和append方法来拼接字符串。
  5. 查找子串:使用find方法查找子串在字符串中的位置。如果找到,返回其起始位置;否则返回std::string::npos

这个示例展示了如何使用C++中的string类进行基本的字符串操作。

上一篇:c++中const的用法

下一篇:c++ typeof

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ weak_ptr

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站