A. 高手请进!如何把整形数据转换为字符串(C语言)
功 能:把一整数转换为字符串
用 法:char *itoa(int value, char *string, int radix);
详细解释:itoa是英文integer to array(将int整型数转化为一个字符串,并将值保存在数组string中)的缩写.
参数:
value: 待转化的整数。
radix: 是基数的意思,即先将value转化为radix进制的数,范围介于2-36,比如10表示10进制,16表示16进制。
* string: 保存转换后得到的字符串。
返回值:
char * : 指向生成的字符串, 同*string。
备注:该函数的头文件是"stdlib.h"
程序例:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int number = 123456;
char string[25];
itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}
注释:编译系统:VC++6.0,TC不支持。
我们可以这样构造itoa()
char* itoa(int i)
{
char *a=malloc(42); /* Enough for a 128 bit integer */
if (a) sprintf(a,"%d",i);
return a;
}
实现itoa函数的源代码
char *my_itoa(int num,char *str,int radix){
const char table[]="";
char *ptr = str;
bool negative = false;
if(num == 0){ //num=0
*ptr++='0';
*ptr='\0'; // don`t forget the end of the string is '\0'!!!!!!!!!
return str;
}
if(num<0){ //if num is negative ,the add '-'and change num to positive
*ptr++='-';
num*=-1;
negative = true;
}
while(num){
*ptr++ = table[num%radix];
num/=radix;
}
*ptr = '\0'; //if num is negative ,the add '-'and change num to positive
// in the below, we have to converse the string
char *start =(negative?str+1:str); //now start points the head of the string
ptr--; //now prt points the end of the string
while(start<ptr){
char temp = *start;
*start = *ptr;
*ptr = temp;
start++;
ptr--;
}
return str;
}
B. C语言 整形变量赋值到字符串
其实用c也很简单的,c里有用于处理字符串的头文件string.h
strcat()函数就是将两个字符串连接
不过在c里面是没字符串变量这个概念的,用字符指针来实现
下面是程序
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
main(){
char
*send
=
"whatyouwant";/*用你想要的东西代替whatyouwant稍改一下可以自己输入,自己完成这个功能吧*/
char
*addr;
addr
=
strcat(send,"@163.com");/*将@163.com连接到send的后面*/
printf("%s",addr);
/*打印结果*/
getch();
}
本人亲自编译通过
C. C语言中如何将数字变成字符串啊
C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。用itoa()函数将整数转换为字符串。
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用的基数。在上例中,转换基数为10。
#include <stdio.h>
int main()
{
int a[4]={1,2,3,4};
char b[4];
for(int i=0;i<4;i++)
b[i]=a[i];
for(int i=0;i<4;i++)
printf("%c",b[i]);
return 0;
}
字符串在存储上类似字符数组
它每一位单个元素都是能提取的,字符串的零位是它的长度,如s[0]=10,这提供给我们很多方便,例如高精度运算时每一位都能转化为数字存入数组。
通常以串的整体作为操作对象,如:在串中查找某个子串、求取一个子串、在串的某个位置上插入一个子串以及删除一个子串等。
两个字符串相等的充要条件是:长度相等,并且各个对应位置上的字符都相等。设p、q是两个串,求q在p中首次出现的位置的运算叫做模式匹配。串的两种最基本的存储方式是顺序存储方式和链接存储方式。
以上内容参考:网络-字符串
D. C语言 将一个整数转换成一个字符串
atoi: 把字符串转换成整型数
itoa:把整数转换为字符串
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int number = 12345;
char string[25];
itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}
哇塞要上面那么复杂吗