C++ :String的三种遍历方式(下标+operator[] 、迭代器、C++11新式for循环)

String的三种遍历方式

string的本质:底层是一个字符串的数组,支持动态增长

把字符串“1234”转换为整形1234

<1>下标+operator[ ] (像数组一样使用)

数组遍历用[]
把"1234"转换成整形

#include <iostream>
#include <string>   //字符串

int StrToIntl(string str)
{
   
    int value = 0;
    for (size_t i = 0; i < str.size(); ++i)
    {
   
        //实现打印
        //cout << str[i] << " ";
        //cout << str.operator[](i) << " ";  //等价上一行 operator[]是函数;(i)是参数;访问底层数组的第i个字符
        value *= 10;
        value += str[i] - '0';   
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解你的要求是将两个字符串用等号连接起来赋值给另外一个字符串。我可以为你实现一个名为`operator=`的函数来达成这个目的: ```c++ #include <iostream> #include <string> using namespace std; int main() { string string1, string2 = "hello", string3 = "world"; string1 = string2 + " " + string3; cout << string1 << endl; // 输出 "hello world" return 0; } ``` 这个程序中,我们首先定义了三个字符串变量`string1`、`string2`和`string3`。然后,我们使用`+`运算符将`string2`和`string3`连接起来,中间用空格隔开。最后,我们将连接后的字符串赋值给`string1`。 如果你需要在你的程序中重载`operator=`函数来实现这个操作,你可以这样写: ```c++ #include <iostream> #include <string> using namespace std; class MyString { private: string str; public: MyString() {} MyString(const string& s) : str(s) {} MyString operator=(const MyString& rhs) { str = rhs.str; return *this; } MyString operator=(const string& s) { str = s; return *this; } friend MyString operator+(const MyString& lhs, const MyString& rhs) { return MyString(lhs.str + rhs.str); } friend MyString operator+(const MyString& lhs, const string& rhs) { return MyString(lhs.str + rhs); } friend MyString operator+(const string& lhs, const MyString& rhs) { return MyString(lhs + rhs.str); } friend ostream& operator<<(ostream& os, const MyString& ms) { os << ms.str; return os; } }; int main() { MyString string1, string2 = "hello", string3 = "world"; string1 = string2 + " " + string3; cout << string1 << endl; // 输出 "hello world" return 0; } ``` 这个程序中,我们定义了一个名为`MyString`的类来表示字符串,重载了`operator=`函数和`operator+`函数。在`operator=`函数中,我们将右操作数的字符串赋值给左操作数的字符串,并返回左操作数的引用。在`operator+`函数中,我们将两个字符串连接起来,并返回一个新的`MyString`对象。最后,我们在`main`函数中使用这些运算符来实现你要求的操作,并输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值