C++字符串string常用函数、技巧

  1. string 与 int 互相转换
    单个互相转换:
#include<string>
//string -> int 
string str="6";//双引号
int a=str[0]-'0';
//int -> string
int a=6;
string str=a+'0';//
	多个转换:

通过stringstream

#include<iostream>
#include<string>
#include<sstream>
using namespace std;
stringstream ss;
int first = 0, second = 0;
ss << "456";  // 插入字符串
ss >> first;  //first=456
ss.clear();  //在进行多次转换前, 必须清除ss
ss << true;
ss >> second;//second=1
//char * 转换
char result[8] ;
stream << 8888; //向stream中插入8888
 stream >> result; //抽取stream中的值到result,屏幕显示 "8888"

参考:
https://blog.csdn.net/sunshineacm/article/details/78068987
http://blog.csdn.net/zhang_xueping/article/details/47846807

  1. char 与 int 互相转换
    多个转换:
#include<stdlib.h>//头文件
    char ch1[10];
    int a=6542;
    //int -> char * ======数字转字符==========
	itoa(a,ch1,10);//    itoa(要转换的数字,保存的字符(串),进制数)
	//char * -> int  =========字符转数字=======
	char ch2[]="123456";
	int b=atoi(ch2);// atoi(要转换的字符(串))
  1. string 与 char 互相转换
    (似乎比较麻烦)
  2. 其他
    char *转 float
#include<stdlib.h>
char ch[]="123.456";
a=atof(ch1);//a=123.456
	sprintf() 函数:

头文件:stdio.h
函数功能:
  (1)将数字变量转换为字符串。
  (2)得到整型变量的16进制和8进制字符串。
  (3)连接多个字符串。
函数原型:int sprintf(char *buffer, const char *format, [argument]…)
参数:
(1)buffer:是char类型的指针,指向写入的字符串指针;
(2)format:格式化字符串,即在程序中想要的格式;
(3)argument:可选参数,可以为任意类型的数据;
函数返回值:buffer指向的字符串的长度;

	#include<stdio.h>
	char ch1[10]="123",ch2[10]="456";
    int a=456,b=789;
    //字符串连接 
	sprintf(ch1,"%s%s",ch1,ch2);
	//数字转字符 
	sprintf(ch1,"%d",a);
	//数字连接
	sprintf(ch1,"%d%d",a,b); 
	//数字+字符 转为字符串 
	sprintf(ch1,"%d=======",a);
	//获取data的十六进制
    sprintf(ch1,"0x%X",a);
    //获取data的八进制
    sprintf(ch1,"0%o",a);
	ssacnf() 函数

sscanf函数原型为int sscanf(const char *str, const char *format, …)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:
  (1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。
  (2)取指定长度的字符串
  (3)取到指定字符为止的字符串
  (4)取仅包含指定字符集的字符串
  (5)取到指定字符集为止的字符串

#include<stdio.h>
char ch1[10]="123",ch2[10]="456";
//取指定长度的字符串
sscanf("zhoue3456 ", "%4s", ch1);//	ch1=zhou 
//取到指定字符为止
sscanf("zhou456 hedf", "%5[^ ]", ch1);// ch1=zhou4
//取遇到空格为止
sscanf("zhou456 hedf", "%8[^ ]", ch1);// ch1=zhou456
//取仅包含指定字符集的字符串
sscanf("654321abcdedfABCDEF", "%[1-9a-z]", ch1); //ch1=654321abcdedf   只取数字和小写字符
 //取到指定字符集为止的字符串
sscanf("BCDEF123456abcdedf", "%[^a-z]", ch1);//ch1=BCDEF123456
//取需要的字符串 
int a,b,c;
sscanf("2015.04.05", "%d.%d.%d", &a,&b,&c);   //  a=2015,b=4,c=5
//给定一个字符串“abcd&hello$why”,现在我想取出&与$之间的字符串怎么办呢
sscanf("abcd&hello$why", "%*[^&]&%[^$]", ch1);//ch1=hello

参考博客:https://blog.csdn.net/zhouwei1221q/article/details/44890617

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值