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

c++ string compare

作者:寂寞味道   发布日期:2026-05-19   浏览:88

#include <iostream>
#include <string>

int main() {
    std::string str1 = "hello";
    std::string str2 = "world";
    std::string str3 = "hello";

    // 比较两个字符串是否相等
    if (str1 == str2) {
        std::cout << "str1 and str2 are equal" << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal" << std::endl;
    }

    // 使用 compare 函数比较两个字符串
    if (str1.compare(str3) == 0) {
        std::cout << "str1 and str3 are equal" << std::endl;
    } else {
        std::cout << "str1 and str3 are not equal" << std::endl;
    }

    // 比较部分字符串
    std::string long_str = "hello world";
    if (long_str.compare(0, 5, "hello") == 0) {
        std::cout << "The first 5 characters of long_str are 'hello'" << std::endl;
    }

    return 0;
}

解释说明:

  1. 字符串相等性比较:使用 == 运算符可以直接比较两个 std::string 是否相等。
  2. compare 函数std::string 类提供了 compare 方法,可以更灵活地进行字符串比较。返回值为 0 表示两个字符串相等,负数表示第一个字符串小于第二个字符串,正数表示第一个字符串大于第二个字符串。
  3. 部分字符串比较compare 方法还可以用于比较字符串的某一部分,例如从指定位置开始的若干字符。

上一篇:c++练习

下一篇:c++ 分割字符串

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

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

Laravel 中文站