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

string c++

作者:仅限对你关心   发布日期:2026-07-27   浏览:42

#include <iostream>
#include <string>

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

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

    // 获取字符串长度
    std::cout << "Length of the string: " << greeting.length() << std::endl;

    // 访问字符串中的单个字符
    std::cout << "First character: " << greeting[0] << std::endl;

    // 连接两个字符串
    std::string part1 = "Hello";
    std::string part2 = "World";
    std::string combined = part1 + ", " + part2 + "!";
    std::cout << "Combined string: " << combined << std::endl;

    // 查找子字符串的位置
    std::string sentence = "This is a sample sentence.";
    size_t position = sentence.find("sample");
    if (position != std::string::npos) {
        std::cout << "Found 'sample' at position: " << position << std::endl;
    } else {
        std::cout << "'sample' not found." << std::endl;
    }

    // 替换子字符串
    std::string text = "C++ is fun.";
    text.replace(0, 3, "Programming");
    std::cout << "Replaced string: " << text << std::endl;

    return 0;
}

解释说明:

  1. 创建字符串对象:使用 std::string 类来创建字符串对象。
  2. 输出字符串:使用 std::cout 输出字符串内容。
  3. 获取字符串长度:使用 length() 方法获取字符串的长度。
  4. 访问单个字符:通过索引访问字符串中的单个字符。
  5. 连接字符串:使用 + 操作符连接两个字符串。
  6. 查找子字符串:使用 find() 方法查找子字符串的位置,如果找不到返回 std::string::npos
  7. 替换子字符串:使用 replace() 方法替换指定位置的子字符串。

以上代码展示了如何在 C++ 中使用 std::string 类进行基本的字符串操作。

上一篇:c++ 单例

下一篇:c++ 字典

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

嵌入式c++

c++框架代码

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

Laravel 中文站