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

c++ string

作者:无声飞雪   发布日期:2025-08-08   浏览:9

#include <iostream>
#include <string>

int main() {
    // 创建一个空的字符串
    std::string emptyString;
    std::cout << "Empty string: '" << emptyString << "'" << std::endl;

    // 使用字符串字面量初始化字符串
    std::string hello = "Hello";
    std::cout << "String initialized with a literal: " << hello << std::endl;

    // 使用另一个字符串初始化
    std::string anotherHello(hello);
    std::cout << "String initialized from another string: " << anotherHello << std::endl;

    // 使用字符数组初始化
    char charArray[] = "C++";
    std::string cppString(charArray);
    std::cout << "String initialized from a character array: " << cppString << std::endl;

    // 字符串拼接
    std::string greeting = hello + " " + cppString;
    std::cout << "Concatenated string: " << greeting << std::endl;

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

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

    // 修改字符串内容
    greeting += "!";
    std::cout << "Modified greeting: " << greeting << std::endl;

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

    return 0;
}

解释说明:

  1. 创建和初始化字符串:展示了如何创建空字符串、使用字符串字面量、另一个字符串或字符数组来初始化 std::string 对象。
  2. 字符串拼接:使用 + 操作符将多个字符串拼接在一起。
  3. 访问字符:通过索引访问字符串中的单个字符。
  4. 获取字符串长度:使用 length() 方法获取字符串的长度。
  5. 修改字符串:通过 += 操作符向字符串末尾添加字符或子字符串。
  6. 查找子字符串:使用 find() 方法查找子字符串的位置,返回其起始位置的索引,如果未找到则返回 std::string::npos

上一篇:c++基础代码

下一篇:c和c++区别

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++ orm框架

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ vector 清空

c++ tcp

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

Laravel 中文站