字符串是面试的重点考察部分的相关知识,通过考察字符串的相关知识可以考察程序员的编程规范以及编程习惯。
一般的字符串库函数包括有: itoa():整型转换为字符串; ltoa():将长整形转换为字符串; ultoa():将无符号长整型转化为字符串;gcvt(): 将浮点型转换为字符串,取四舍五入; ecvt():将双精度浮点型转换为字符串;以及sprintf()系列函数,但sprintf函数的运行速度比以上函数慢。
1. 整形与字符串的转化。
1void itoa(int SrcNum, char *DestStr) //原函数要复杂很多
2{
3 int i=0, j=0;
4 char tmpstr;
5 int tmpnum = (SrcNum > 0) ? StrNum : -StrNum;
6 if(DestStr==NULL)
7 return;
8 while(tmpnum!=0)
9 {
10 DestStr[i++] = StrNum%10 + '0';
11 StrNum = StrNum/10;
12 }
13 if(tmpnum < 0)
14 DestStr[i++] = '-';
15 DestStr[i] = '\0';
16 i--;
17 while(i!=j)
18 {
19 tmpstr = DestStr[i];
20 DestStr[i] = DestStr[j];
21 DestStr[j] = tmpstr;
22 i++;
23 j++;
24 }
25}
2{
3 int i=0, j=0;
4 char tmpstr;
5 int tmpnum = (SrcNum > 0) ? StrNum : -StrNum;
6 if(DestStr==NULL)
7 return;
8 while(tmpnum!=0)
9 {
10 DestStr[i++] = StrNum%10 + '0';
11 StrNum = StrNum/10;
12 }
13 if(tmpnum < 0)
14 DestStr[i++] = '-';
15 DestStr[i] = '\0';
16 i--;
17 while(i!=j)
18 {
19 tmpstr = DestStr[i];
20 DestStr[i] = DestStr[j];
21 DestStr[j] = tmpstr;
22 i++;
23 j++;
24 }
25}
2. 字符串转换为整型
1int strtoint(const char *SrcStr)
2{
3 int tmpnum = 0;
4 const char *tmpstr = SrcStr;
5 if(StcStr==NULL)
6 return;
7 if(*SrcStr=='-')
8 tmpstr++;
9 while(*tmpstr!='\0')
10 {
11 if(*tmpstr<'0' || *tmpstr>'9')
12 return;
13 tmpnum = tmpnum*10 + (*tmpstr - '0');
14 tmpstr++;
15 }
16 if(*SrcStr=='-')
17 tmpnum = -tmpnum;
18 return tmpnum;
19}
2{
3 int tmpnum = 0;
4 const char *tmpstr = SrcStr;
5 if(StcStr==NULL)
6 return;
7 if(*SrcStr=='-')
8 tmpstr++;
9 while(*tmpstr!='\0')
10 {
11 if(*tmpstr<'0' || *tmpstr>'9')
12 return;
13 tmpnum = tmpnum*10 + (*tmpstr - '0');
14 tmpstr++;
15 }
16 if(*SrcStr=='-')
17 tmpnum = -tmpnum;
18 return tmpnum;
19}