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

c++字符串

作者:妖孽少年   发布日期:2025-05-06   浏览:31

#include <iostream>
#include <string>

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

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

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

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

    // 字符串拼接
    std::string name = "C++";
    std::string welcomeMessage = greeting + " Welcome to " + name;
    std::cout << welcomeMessage << std::endl;

    // 查找子字符串
    size_t pos = welcomeMessage.find("Welcome");
    if (pos != std::string::npos) {
        std::cout << "Found 'Welcome' at position: " << pos << std::endl;
    } else {
        std::cout << "'Welcome' not found" << std::endl;
    }

    // 替换子字符串
    std::string replaced = welcomeMessage.replace(pos, 7, "Greetings");
    std::cout << "After replacement: " << replaced << std::endl;

    return 0;
}

解释说明:

  1. 创建字符串对象:使用 std::string 类型创建字符串对象,例如 std::string greeting = "Hello, World!";
  2. 输出字符串:使用 std::cout 输出字符串的内容。
  3. 获取字符串长度:使用 length() 方法获取字符串的长度。
  4. 访问单个字符:通过索引访问字符串中的单个字符,例如 greeting[0]
  5. 字符串拼接:使用 + 操作符将多个字符串连接在一起。
  6. 查找子字符串:使用 find() 方法查找子字符串的位置。如果找到返回位置索引,否则返回 std::string::npos
  7. 替换子字符串:使用 replace() 方法替换指定位置的子字符串。

这段代码展示了 C++ 中常用的字符串操作方法。

上一篇:c++入门

下一篇:c++指针

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ 树

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

Laravel 中文站