字符转换(C、C++)

标准C和C++库提供了一些转换工具。但是它们在易用性、扩展型和安全型上各有不同。
例如,以atoi为代表的一系列标准C函数就有一些限制:
* 只支持单向转换:从文本到内部数据类型。要用C库函数实现另一个方向的转换,要么使用不太方便并且有损安全性的sprintf,要么牺牲可移植性,使用非标准函数,例如itoa。 
* 支持的类型只是内建数值类型的一个子集,即int、long和double。 
* 支持的类型不能用统一的方式扩展。例如从字符串表示转为complex或者rational。
以strtol为代表的标准C函数也有同样的基本限制,但它们对转换过程提供了更好的控制。然而,通常情况下这样的控制既不需要也没人用。scanf系列函数甚至提供了更多的控制,但同样缺少安全性和易用性。
标准C++库为这种转换提供了stringstream。它提供了大量格式控制,并且可以通过以文本中介进行任意类型之间的转换。但是对于简单转换,直接用stringstream可能显得很笨拙(引入额外的局部变量,并失去了嵌在表达式里使用的方便性),或者很难懂(在表达式里创建stringstream的临时对象)。Facets为控制文本的表现形式提供了全面的概念和机制,但是它相对较高的门槛使简单转换也牵涉到太深的技术。
lexical_cast模板函数提供了方便而且统一的形式来进行任意类型(当它们可以表示为文本)之间的转换。因为你可以把这种转换方便地写在表达式内,所以它可以简化你的程序。对于更复杂的转换,例如需要对精度或者格式作一些比lexical_cast缺省行为更严格的控制时,那么还是建议你用常规的stringstream方法。如果是数值到数值的转换,numeric_cast的行为要比lexical_cast更合理些
 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int tonum(char *string)
{
 int n=0,i;
 if(*string=='-')
     i=-1;
 else
  i=1;
 while(!(*string>='0'&&*string<='9'))
  string++;
 while(*string>='0'&&*string<='9')
 {
  n*=10;
  n+=*string-'0';
  string++;
 }
 return n*i;
}
char * tostring(int n,char *p)
{
 char *q;
 char *str=(char*)malloc(20);
 if(p==NULL)
  return NULL;
 if(n<0)
 {
  strcpy(str,"-");
     n=abs(n);
 }
 else
  strcpy(str,"");
 p[0]=n/10000+'0';
 n=n%10000;
 p[1]=n/1000+'0';
 n=n%1000;
 p[2]=n/100+'0';
 n=n%100;
 p[3]=n/10+'0';
 n=n%10;
 p[4]=n+'0';
 p[5]='';
 q=p;
 while(*q!=''&&*q=='0')
  q++;
 if(*q=='')
  return p;
 strcpy(p,q);
 if(!strcmp(str,"-"))
 {
  strcat(str,p);
  strcpy(p,str);
 }
 free(str);
 return p;
}
int main()
{
 char *string=new char[20];
 strcpy(string,"-123");
 printf("%d
",tonum(string));
 printf("--------------------------
");
 printf("%s",tostring(-123,string));
 getchar();
 delete string;
 return 0;
}
 
 

#include <windows.h>
#include <iostream>
using std::cout;  
using std::cin;
using std::endl;
void int2str(int n,char * &p);
void str2int(const char *str,int& num);
int main()
{
 //int to string
    int num;
    char* p=NULL;
 cout<<"input a num:";
 cin>>num;
    int2str(num,p);
 cout<<p<<endl;
 //string to int
 char arr[10];
 char *buf=arr;
 cout<<"input a string that is num:";
 cin>>buf;
 int n=0;
 str2int(buf,n);
 cout<<n;
 system("pause");
 return 0;
}
void int2str(int n,char * &p)
{
 int i=0,len=0;
 char buf[20];
 memset(buf,0,sizeof(buf)/sizeof(buf[0]));
 int temp=(n<0?
  -n:n);
 while(temp)
 {
  buf[i++]=temp%10+'0';
  temp=temp/10;
 }
 len=i;
 if(n<0)
 {
  p=(char *)malloc(len*sizeof(char)+2);
  p[0]='-';
  for(i=len-1;i>=0;i--)
  {
   p[len-i]=buf[i];
  }
  p[len+1]='';
 }
 else
 {
  p=(char *)malloc(len*sizeof(char)+1);
  for(i=len-1;i>=0;i--)
  {
   p[len-i-1]=buf[i];
  }
  p[len]='';
 }
}
void str2int(const char *str,int& num)
{
    const char *p=str;
   int temp=0;
   if(*p>'9'||*p<'0')
    ++p;
    int len=strlen(p);
 for(int i=0;i<len;i++)
 {
  temp=temp*10+(*p++ - '0');
 }
 num=(*str=='-'?(-temp):temp);
}

int  atoi(const  char  *s)
{
      char  *p  =  s;
      char  c;
      int  i  =  0;
      while(c=*p++)
      {
            if(c>='0'  &&  c <='9')
            {
                  i  =  i*10  +  (c-'0');
            }
            else
                  return  -1;                    //Invalid  string
      }
      return  i;
}
********************************************************************************************
itoa       把一整数转换为字符串
例程序:
#include <ctype.h>
#include <stdio.h>
void        itoa (int n,char s[]);
//atoi 函数:将s转换为整形数
int main(void )
{   
int n;
char s[100];
printf("Input n:
");
scanf("%d",&n);
          printf("the string : 
");
          itoa (n,s);
return 0;
}
void itoa (int n,char s[])
{
int i,j,sign;
if((sign=n)<0)//记录符号
        n=-n;//使n成为正数
          i=0;
do{
        s[i++]=n%10+'0';//取下一个数字
}while ((n/=10)>0);//删除该数字
if(sign<0)
        s[i++]='-';
s[i]='';
for(j=i;j>=0;j--)//生成的数字是逆序的,所以要逆序输出
        printf("%c",s[j]);
 
}
 
java 怎样把字符串数组如 String array[]={"5555","6666","2222","9999","1111"};
转化成int型的 5555  6666  2222  9999  1111?
String array[] = { "5555", "6666", "2222", "9999", "1111" };
  int[] number = new int[array.length];
  for (int i = 0; i < array.length; i++) {
   int num = Integer.parseInt(array[i]);// 转换
   number[i] = num;
  }
  System.out.println(number.length);
 
 
 
1    # include <stdio.h>
2    # include <stdlib.h>
3    
4    int main ()
5    {
6        int num_int;
7        double num_double;
8        char str_int[30] = "435";         //将要被转换为整型的字符串
9        char str_double[30] = "436.55";  //将要被转换为浮点型的字符串
10   
11       num_int = atoi(str_int);          //转换为整型值
12       num_double = atof(str_double);  //转换为浮点型值
13   
14       printf("num_int: %d
", num_int);
15       printf("num_double: %lf
", num_double);
16   
17       return 0;
18   }
 
1    #include <iostream>2    using namespace std;3    4    int str2int(const char *str)5    {6        int temp = 0;7        const char *ptr = str;  //ptr保存str字符串开头8    9        if (*str == '-' || *str == '+')  //如果第一个字符是正负号,10       {                      //则移到下一个字符11           str++;12       }13       while(*str != 0)14       {15           if ((*str < '0') || (*str > '9'))  //如果当前字符不是数字16           {                       //则退出循环17               break;18           }19           temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值20           str++;      //移到下一个字符21       }    22       if (*ptr == '-')     //如果字符串是以"-"开头,则转换成其相反数23       {24           temp = -temp;25       }26   27       return temp;28   }29   30   int main()31   {32       int n = 0;    33       char p[10] = "";34   35       cin.getline(p, 20);   //从终端获取一个字符串36       n = str2int(p);      //把字符串转换成整型数37       38       cout << n << endl;39   40       return 0;41   }
原文地址:https://www.cnblogs.com/amwuau/p/6255531.html