字符串处理函数

面试中面试官会经常让你现场写的程序主要集中在字符串处理函数的实现上:

1、字符串的复制

2、字符串的连接

3、字符串的比较

详见:点击打开链接

4、字符串的查找(查找一个字符串在另一字符串中的位置)

5、字符串的转换(atoi函数、atof函数)

前三个函数的实现都比较容易,但必须注意的一点是:一定要注意字符串结束标识符是否需要人为的添加到目的字符串中。

字符串的查找,其实就是模式匹配,数据结构中讲到高效的KMP算法。

这里我重点说下字符串的转换函数:

atoi:数字字符串转换为相应的整数,如“2345”=>2345

int atoi(char s[])
{
    int result=0;
    while(s[i])
        result = 10 * result + (s[i] - '0');
    return result;
}

反过来,itoa:整数转换为相应的数字字符串,如2345=>"2345"

void itoa(int n)
{
    int m;
    if(n)
    {
	m=n%10;
        n/=10;
	itoa(n);
    }
    printf("%c",m+'0');//将相应的数字转化为相应的数字字符,如将3转化为’3’

}
atof:数字字符串转换为相应的浮点型数,如“123.45”=>123.450000,"123.45E+02"=>12345.000000等等

#include 
#include 
double atof(char s[])
{
    int i=0,k,m;
    double result=0;
    int result1=0;

    //处理整数部分
    while(s[i]!='\0')
    {
        if(s[i]!='.')
            result = 10.0 * result + (s[i] - '0');
        else
            break;
        i++;
    }

    //假如有小数部分,计算整数+小数部分
    if(s[i]!='\0')
    {
        i++;
        m=0;
        while(s[i]!='\0')
        {
            if(s[i]!='E' && s[i]!='e')
            {
                m++;
                result+= (s[i] - '0')*pow(0.1,m);
            }
            else
                break;
            i++;
        }

    }

    //假如有'e'之后的部分
    if(s[i]!='\0')
    {
        i++;
        while(s[i]!='\0')
        {
            if(s[i]=='+' || s[i]=='-')
                k=i;//记录'+'或'-'的位置
            else
                result1 = 10 * result1 + (s[i] - '0');
            i++;
        }
        if(s[k]=='-')
            result1=-result1;
        result*=pow(10,result1);
    }

    return result;
}
int main()
{
    char s[100];
    while(1)
    {
        printf("please input a string:");
        gets(s);
        printf("%lf\n",atof(s));
    }
    return 0;
}
字符串处理函数_第1张图片


你可能感兴趣的:(数据结构,C语言,C++)