C++字符串操作

本文介绍了C++中用于字符串操作的基础函数,包括strcmp进行字符串比较,to_string将数字转换为字符串,字符串相加使用s1.append(s2),以及char转int的ASCII码应用和string转int的stoi函数。
摘要由CSDN通过智能技术生成

1. 字符串比较 strcmp

  • 头文件 string.h
  • 变量需要传指针;
  • 返回>0 则第一个字符串比第二个字符串大,反之则小,=0则表示两个字符串相同。
# include <iostream>
# include <stdio.h>
# include <string.h>

using namespace std;

int main() {
    
    string s = "123";
    char* p = &s[0];
    // char* p = "123"; // 或者
    
    if (!strcmp(p, "123")) {
        printf("%s \n", p);
    }
    
    printf("%d", strcmp("213", "123"));
    
    return 0;
}
/**
123 
1
*/

2. 转为字符串类型 to_string

# include <iostream>
# include <string>

using namespace std;

int main() {
    cout<<to_string(1.1);
    return 0;
}
// 1.100000

3. 字符串相加

  • s1 + s2
  • s1.append(s2)
# include <iostream>
# include <stdio.h>

using namespace std;

int main() {
    
    string s1 = "123";
    string s2 = "45";
    
    cout << s1 + s2<<endl;
    
    s1.append(s2);
    cout << s1;
    
    return 0;
}

4. char 转 int s-‘0’

  • '9' - '0' >>> 9
  • int('1') >>> 49(ascii 码)

5. string 转 int stoi()

# include <iostream>
using namespace std;

int main() {
    string s = "23";
    cout<<stoi(s);
    return 0;
}
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值