C++_char/string 转换成 int/float char大小写转换

本文仅仅发布在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;
}
运行结果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值