版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shanghairuoxiao/article/details/78631814
字符串与数字之间转换
数字转字符串
数字转字符串有以下几种方法
1. sprintf
sprint函数如下所示:
sprintf(buffer, "a = %d", a);
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, c;
scanf("%d%d%d",&a, &b, &c);
printf("a = %d, b = %d, c = %d", a, b, c);
char buffer[256];
memset(buffer, '\0', 256);
sprintf(buffer, "%d", a);
cout << buffer;
system("pause");
return 0;
}
char str[10];
double a=123.321;
sprintf(str,"%.3lf",a);
itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
3. itoa实现整形转字符
itoa(int, char*, 10);
第一个参数是被转的整形,第二是字符串指针,第三个是进制
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, c;
scanf("%d%d%d",&a, &b, &c);
printf("a = %d, b = %d, c = %d", a, b, c);
char buffer[256];
memset(buffer, '\0', 256);
itoa(a, buffer, 10);
cout << buffer;
system("pause");
return 0;
}
字符串转数字
1. sscanf
char str[]="1234321";
int a;
sscanf(str,"%d",&a);
.............
char str[]="123.321";
double a;
sscanf(str,"%lf",&a);
.............
char str[]="AF";
int a;
sscanf(str,"%x",&a); //16进制转换成10进制
char temp[256] = "12345";
int c = 0;
c = atoi(temp);
sscanf(temp, "%['\0']", c);
cout << c;
system("pause");
return 0;
另外也可以使用atoi(),atol(),atof().
1、一般用法
char buf[512] = ;
sscanf("123456 ", "%s", buf);
printf("%s\n", buf);
结果为:123456
2. 取指定长度的字符串。如在下例中,取最大长度为4字节的字符串。
sscanf("123456 ", "%4s", buf);
printf("%s\n", buf);
结果为:1234
3. 取到指定字符为止的字符串。如在下例中,取遇到空格为止字符串。
sscanf("123456 abcdedf", "%[^ ]", buf);
printf("%s\n", buf);
结果为:123456
4. 取仅包含指定字符集的字符串。如在下例中,取仅包含1到9和小写字母的字符串。
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf);
printf("%s\n", buf);
结果为:123456abcdedf
5. 取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。
sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf);
printf("%s\n", buf);
结果为:123456abcdedf
6、给定一个字符串iios/12DDWDFF@122,获取 / 和 @ 之间的字符串,先将 "iios/"过滤掉,再将非'@'的一串内容送到buf中
sscanf("iios/12DDWDFF@122", "%*[^/]/%[^@]", buf);
printf("%s\n", buf);
结果为:12DDWDFF
7、给定一个字符串"hello, world",仅保留"world"。(注意:“,”之后有一空格)
sscanf(“hello, world”, "%*s%s", buf);
printf("%s\n", buf);
结果为:world
P.S. %*s表示第一个匹配到的%s被过滤掉,即hello被过滤了,
如果没有空格则结果为NULL。
string转char*
string str;
char* ch;
char *ch = const_cast<char*>(str.c_str());
char*转string*
直接转
char *ch = "12345";
string str(ch);
字符串操作
strcpy, strcat, strcam
使用stringstream类
用ostringstream对象写一个字符串,类似于sprintf()
ostringstream s1;
int i = 22;
s1 << "Hello " << i << endl;
string s2 = s1.str();
cout << s2;
用istringstream对象读一个字符串,类似于sscanf()
istringstream stream1;
string string1 = "25";
stream1.str(string1);
int i;
stream1 >> i;
cout << i << endl; // displays 25