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

c++字符串比较

作者:叶枫殇   发布日期:2025-11-08   浏览:90

#include <iostream>
#include <string>

int main() {
    // 定义两个字符串
    std::string str1 = "hello";
    std::string str2 = "world";

    // 使用比较运算符比较字符串
    if (str1 == str2) {
        std::cout << "str1 和 str2 相等" << std::endl;
    } else if (str1 < str2) {
        std::cout << "str1 小于 str2" << std::endl;
    } else {
        std::cout << "str1 大于 str2" << std::endl;
    }

    // 使用 compare 函数比较字符串
    int result = str1.compare(str2);
    if (result == 0) {
        std::cout << "str1 和 str2 相等" << std::endl;
    } else if (result < 0) {
        std::cout << "str1 小于 str2" << std::endl;
    } else {
        std::cout << "str1 大于 str2" << std::endl;
    }

    return 0;
}

解释说明:

  1. 定义字符串:使用 std::string 类型定义了两个字符串 str1str2
  2. 比较运算符:使用 ==, <, > 等运算符直接比较两个字符串的内容。这些运算符会根据字典顺序进行比较。
  3. compare 函数std::string 类提供了一个 compare 成员函数,用于比较两个字符串。返回值为 0 表示相等,负数表示第一个字符串小于第二个字符串,正数表示第一个字符串大于第二个字符串。

通过这两种方式,你可以轻松地在 C++ 中比较字符串。

上一篇:c++ dll

下一篇:c++ emplace_back

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

进制转换c++代码

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

Laravel 中文站