C++中的string注意事项

字面值和string相加

  做加法运算时,字面值和字符都会被转化成string对象,因此直接相加就是将这些字面值串联起来:

                       string s1="hello",s2="world" //在s1和s2中都没有标点符号

                        string s3=s1+","+s2+'\n'

        当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保每个加法运算符的两侧的运算对象至少有一个是string;

                         string       s4=s1+","; //正确;把一个string对象和有一个字面值相加

                         string         s5="hello"+",";//错误;两个运算对象都不是string

                         string        s6=s1+","+"wrold";//正确,每个加法运算符号都有一个是string

                          string        s7="world"+","+s1;//错误,不能把字面值直接相加,运算从左到右进行的

C++独特的遍历string方式;

//C++范围遍历
string s="hello world"
for(char c: s)
{
    cout<<c<<endl;
}
//等价于
for(int i=0;i<s.size();i++)
{
    char c=s[i];
}

//当我们想改变里面的值的时候,加一个&
for(char &c: s)
{
    c='a';
}

 定义string a[10000]那么里面a[0]每一个都是string 类型

string a[10000];
int main()
{
    string b;
    while(cin>>a[i])
    {
        if(a[i]==b)//因为a[i]里每个都是string 类型,所以可以进行比较,此时的是string           与string进行比较
        {
              cout<<b<<endl;
        }
    }
}

                string s1, s2;、

                s1.find(s2);
                // 在 s1 中查找字符串 s2,找到返回 s2 首字母在字符串中的下标,找不到返回 -1

                s1.replace(pos, len, s2);
                // 把 s1 中从下标 pos 开始的长度为 len 的子串替换为 s2

                s1.erase(it);
                // 把 s1 字符串中迭代器 it 处的字符删除

                s1.erase(pos, len);
                // 把 s1 中从下标 pos 开始的长度为 len 的子串删除

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ string 类型是一个非常常用的字符串类,可以方便地进行字符串的操作。使用 string 类型需要注意以下几点: 1. 头文件:需要包含 <string> 头文件。 2. 声明:需要使用 std 命名空间,或者在全局范围内使用 using namespace std; 声明。 3. 初始化:可以直接使用字符串字面量或者其他 string 对象初始化。 4. 操作:可以使用常规的字符串操作,如比较、拼接、查找、替换等。 5. 长度:可以使用 size() 或者 length() 方法获取字符串的长度。 6. 遍历:可以使用 for 循环或者迭代器遍历字符串的每一个字符。 7. 转换:可以使用 c_str() 方法将 string 类型转换为 const char* 类型,或者使用 stoi()、stof() 等方法将 string 类型转换为其他类型。 示例代码: ``` #include <iostream> #include <string> using namespace std; int main() { string s1 = "hello"; string s2("world"); string s3 = s1 + " " + s2; cout << s3 << endl; if (s1 == "hello") { cout << "s1 equals to hello" << endl; } int index = s3.find("world"); if (index != string::npos) { cout << "world found at index " << index << endl; } for (char c : s3) { cout << c << " "; } cout << endl; const char* cstr = s3.c_str(); cout << "cstr: " << cstr << endl; return 0; } ``` 输出结果: ``` hello world s1 equals to hello world found at index 6 h e l l o w o r l d cstr: hello world ``` 需要注意的是,string 类型的底层实现是动态分配的内存,因此在进行大量字符串操作时需要注意内存的使用。同时,由于 string 对象的复制和传递会涉及到内存的拷贝,因此也需要注意效率问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值