您的当前位置:首页C++字符串变量的运算

C++字符串变量的运算

来源:锐游网

在C++中,我们可以使用字符串变量进行多种运算操作,包括连接、比较和查找等。下面是一些常见的C++字符串变量运算:

  • 连接字符串:可以使用加号运算符将两个字符串连接起来。例如:

    string str1 = "Hello, ";
    string str2 = "world!";
    string result = str1 + str2;  // 结果为 "Hello, world!"
    
  • 比较字符串:可以使用比较运算符(如==、!=、<、>、<=、>=)来比较两个字符串的大小关系。例如:

    string str1 = "apple";
    string str2 = "banana";
    if (str1 < str2) {
        // 执行语句
    }
    
  • 获取字符串长度:可以使用length()或者size()函数来获取字符串的长度。例如:

    string str = "Hello";
    int len = str.length();  // len的值为5
    
  • 访问字符串中的字符:可以通过下标运算符[]来访问字符串中的特定字符。例如:

    string str = "C++";
    char ch = str[1];  // ch的值为'+'
    
  • 查找子字符串:可以使用find()函数来查找字符串中是否包含特定的子字符串,并返回其位置。例如:

    string str = "Hello, world!";
    size_t pos = str.find("world");  // pos的值为7
    

使用 + 运算符连接两个字符串变量

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello, ";
    string str2 = "world!";
    string result = str1 + str2;
    cout << result << endl;  // 输出 "Hello, world!"
    return 0;
}

在这个例子中,我们声明了两个字符串变量 str1str2,并将它们连接起来赋值给了另一个字符串变量 result。然后通过 cout 输出 result 的值,即 “Hello, world!”。

因篇幅问题不能全部显示,请点此查看更多更全内容

Top