面试题1234转为1_2_3_4(实现itoa函数)的另一方法
2008-03-14 12:45
197 查看
其实这道题目所白了就是将整型数转化为字符型。思路和前一篇文章类似:
对整数取关于10的模,然后加上‘/0’标识符作为字符串的结束。因为在一个整形之后加上'0',系统会将隐式转为字符型。当然在C/C++库中有一个itoa函数能够实现这个功能,但若要求不调用该代码,而是自己实现,可参考如下:
代码如下:
#include<iostream>
using namespace std;
int main(void)
{
int num;
char temp[7],str[7];
int i,j;
i = 0;j = 0;
cin >> num;
while(num)
{
temp[i] = num%10 + '0';
i++;
num = num/10;
}
// or temp[i] = 0; is ok too!
temp[i] = '/0';
cout << "now the int num is converted" << temp << endl;
i = i - 1;
//processin the int to string
while(i >= 0)
{
str[j] = temp[i];
j++;
i--;
}
//or str[j] = 0; is ok too!
str[j] = '/0';
for(int k = 0; k < j-1 ; k++)
cout << str[k] <<"_";
cout << str[j-1] << endl;
return 0;
}
关于这段代码,有以下一些说明:
1.字符数组初始化问题:
字符数组有两种初始化形式:
char ch[];
ch[] = "12345";
ch[] = {'1' , '2', '3', '4' '5'};
第一种称为字符串初始化,系统会默认在结尾处添加/0作为额外的终止空字符。即这种方法初始化的ch是6维的。
第二种称为花括号初始化,单个字符并不需要添加额外的终止空字符,此时ch是5维的。
用以下代码来进行以下验证:
#include<iostream.h>
void main()
{
char ch1[] = "12345";
char ch2[] = {'1','2','3','4','5'};
cout <<"length of ch1:" << sizeof(ch1) << endl;
cout <<"length of ch2:" << sizeof(ch2) << endl;
}
运行结果为:
length of ch1:6
length of ch2:5
2.字符串end
在代码中temp[i] = 0和temp[j] = '/0';是等价的。
对整数取关于10的模,然后加上‘/0’标识符作为字符串的结束。因为在一个整形之后加上'0',系统会将隐式转为字符型。当然在C/C++库中有一个itoa函数能够实现这个功能,但若要求不调用该代码,而是自己实现,可参考如下:
代码如下:
#include<iostream>
using namespace std;
int main(void)
{
int num;
char temp[7],str[7];
int i,j;
i = 0;j = 0;
cin >> num;
while(num)
{
temp[i] = num%10 + '0';
i++;
num = num/10;
}
// or temp[i] = 0; is ok too!
temp[i] = '/0';
cout << "now the int num is converted" << temp << endl;
i = i - 1;
//processin the int to string
while(i >= 0)
{
str[j] = temp[i];
j++;
i--;
}
//or str[j] = 0; is ok too!
str[j] = '/0';
for(int k = 0; k < j-1 ; k++)
cout << str[k] <<"_";
cout << str[j-1] << endl;
return 0;
}
关于这段代码,有以下一些说明:
1.字符数组初始化问题:
字符数组有两种初始化形式:
char ch[];
ch[] = "12345";
ch[] = {'1' , '2', '3', '4' '5'};
第一种称为字符串初始化,系统会默认在结尾处添加/0作为额外的终止空字符。即这种方法初始化的ch是6维的。
第二种称为花括号初始化,单个字符并不需要添加额外的终止空字符,此时ch是5维的。
用以下代码来进行以下验证:
#include<iostream.h>
void main()
{
char ch1[] = "12345";
char ch2[] = {'1','2','3','4','5'};
cout <<"length of ch1:" << sizeof(ch1) << endl;
cout <<"length of ch2:" << sizeof(ch2) << endl;
}
运行结果为:
length of ch1:6
length of ch2:5
2.字符串end
在代码中temp[i] = 0和temp[j] = '/0';是等价的。
相关文章推荐
- PHP实现全角字符转为半角方法汇总
- jquery.form.js实现将form提交转为ajax方式提交的方法
- CImage类的介绍与使用 【图像打开,另存为,转为灰度图像(利用cimage方法实现)】
- 利用数据结构中的桟 实现十进制 转为 二 到 十六 之间任何进制 的方法
- 剑指Offer面试题33:把数组排成最小的数 Java 实现,三种方法
- 【面试题】两种方法实现strcpy
- 56-58_数组_StringBuilder和StringBuffer_常用方法_方法链的实现_JDK源码分析_常见面试题
- 【面试题】判断回文数-两种方法实现
- php将HTML表格每行每列转为数组实现采集表格数据的方法
- 用Swig将c/c++程序转为java代码(使用swig实现java调用c、c++的方法)
- jquery.form.js实现将form提交转为ajax方式提交的使用方法
- java中两个对象间的属性值复制,比较,转为map方法实现
- CImage类的介绍与使用 【图像打开,另存为,转为灰度图像(利用cimage方法实现)】
- 面试题:单链表逆置(分别用非递归和递归两种方法实现)
- 面试题:用三种方法模拟实现strlen函数
- python实现将读入的多维list转为一维list的方法
- 经典面试题:设计包含min函数的栈,O(1)空间实现方法
- atoi和itoa函数的实现方法
- php实现将上传word文件转为html的方法