C++中compare,assign ,itoa,c_str等字符串函数的使用

compare()比较函数

#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::endl;
using std::cin;
using std::string;
int main(void){
  string str1="hi,test,hello";
  string str2="hi,test";
  //字符串比较
  if(str1.compare(str2)>0)
    printf("str1>str2\n");
  else if(str1.compare(str2)<0)
    printf("str1<str2\n");
  else
    printf("str1==str2\n");
  
  //str1的子串(从索引3开始,包含4个字符)与str2进行比较
  if(str1.compare(3,4,str2)==0)
    printf("str1的指定子串等于str2\n");
  else
    printf("str1的指定子串不等于str2\n");
  
  //str1指定子串与str2的指定子串进行比较
  if(str1.compare(3,4,str2,3,4)==0)
    printf("str1的指定子串等于str2的指定子串\n");
  else
    printf("str1的指定子串不等于str2的指定子串\n");
  
  //str1指定子串与字符串的前n个字符进行比较
  if(str1.compare(0,2,"hi,hello",2)==0)
    printf("str1的指定子串等于指定字符串的前2个字符组成的子串\n");
  else
    printf("str1的指定子串不等于指定字符串的前2个字符组成的子串\n");
  return 0;
}

   itoa函数的使用------------------------------注意linux平台下没有这个函数,Windows下才有,跨平台要用sprintf

#include<cstdlib>
#include<cstdio>
int main() { int num = 10; char str[100]; itoa(num, str, 2); printf("%s\n", str); return 0; }
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制……
于是想到了一个十进制转二进制的方法:
#include<cstdlib>
#include<cstdio>
int main() { int num = 10; char str[100]; int n = atoi(itoa(num, str, 2)); printf("%d\n",n); return 0; }
先把num转换为二进制的字符串,再把该字符串转换为整数。

c_str

语法: 
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同. 
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针 
比如:最好不要这样: 
char* c; 
string s="1234"; 
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理,同时,编译器也将报错——将一个const char *赋与一个char *。

应该这样用: 
char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作

再举个例子
c_str() 以 char* 形式传回 string 内含字符串
如果一个函数要求char*参数,可以使用c_str()方法: 
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!"






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值