本文仅仅发布在CSDN我的博客:点击打开链接。
http://blog.csdn.net/pythontojava?viewmode=contents
转载请注明出处。
我用的IDE是VS2013.。代码在vc++6.0不能编译,要把int _tmain(int argc, _TCHAR* argv[]) 改成 int main() 。
1.单个char转换成int
// char ------>int
#include<iostream>
#include<string>
using namespace std;
int single_char_to_int(char c)//将以char型存储的数字转换成int型10进制数字
{
int result =-1;
if (c >= '0'&&c <= '9')//如果char变量代表着数字,则转换成int,不是数字则返回-1
{
result = c - 48;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<single_char_to_int('9');
system("pause");
return 0;
}
运行结果:
=======分割线=========
2.将字符数组里的整数转换成int.
\\char c[6]---->int
本函数可以自动把字符数组里的非数字去除。
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int char_array_to_int(char *c)//将字符数组类型的整数转换成int类型的函数
{
int n = strlen(c) - 1;//字符数组长度-1
int i =0, result = 0;
while (i<=n)
{
if (c[i] >= '0'&&c[i] <= '9')
{
result = result * 10 + c[i] - 48;
}
i++;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
char c[6] = "1314";
cout << char_array_to_int(c);
cout << endl;
system("pause");
return 0;
}
运行结果:
=======分割线=========
3.将字符串里的数字转换成整型数字
本函数可以自动把字符串里的非数字去除。
//string ---> int
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int string_to_int(string s)
{
int n = s.size()- 1;//字符串长度-1
int i = 0, result = 0;
while (i <= n)
{
if (s[i] >= '0'&&s[i] <= '9')
{
result = result * 10 + s[i] - 48;
}
i++;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
string s = "189";
cout<<string_to_int(s);
cout << endl;
system("pause");
return 0;
}
运行结果:
==========分割线==============
4.char大写字母转小写,小写转大写
//‘A’----->'a' 'b'---->'B'
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
char char_down(char c)//大写字母转小写函数
{
if (c >= 'A'&&c <= 'Z')//如果字符是大写字母则转换,否则不变输出
{
c = c+32;
}
return c;
}
char char_up(char c)//小写字母转大写函数
{
if (c >= 'a'&&c <= 'z')
{
c = c-32;
}
return c;
}
int _tmain(int argc, _TCHAR* argv[])
{
char c1 = 'a', c2 = 'B';
char c3 = char_up('c');
cout << char_up(c1) << endl;
cout << char_down(c2) << endl;
cout << c3<<endl;
system("pause");
return 0;
}
运行结果: