字符串训练——求字符串长度、去掉空格

来源:互联网 发布:工资考勤软件 验厂 编辑:程序博客网 时间:2024/05/20 07:33

1、求字符串的长度

int main(){    char str[100] = "hello world";    int len = 0;#if 0    int i;    for (i = 0; i < 100; i++)    {        if (str[i] != '\0')            len++;        else            break;    }    while(str[len])    {        len++;    }#endif      while(str[len++]);    len--;    printf ("%d\n", len);    return 0;}

2、求中英混合字符串长度

int main(){    char str[] = "abc你好世界";    int i = 0;    int len = 0;    while (str[i])    {           if (str[i] < 0)             i += 2;        i++;        len++;    }    printf ("%d\n", sizeof(str));    printf ("%d\n", len);    return 0;}

3、去掉字符串右边的空格

int main1(){    char str[100] = "hello world       ";    int len = 0;    while(str[len])        len++;    int i = len-1;    while (str[i] == ' ')    {        i--;    }    str[i+1] = '\0';    printf ("%s1111111111\n", str);    return 0;}

4、去掉字符串左边的空格

int main(){    char str[100] = "        hello world";    int i = 0;    int j = 0;    while (str[i] == ' ')        i++;    while (str[i])    {        str[j++] = str[i++];    }    str[j] = '\0';    printf ("%s\n", str);    return 0;}
原创粉丝点击