Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97588
  • 博文数量: 65
  • 博客积分: 2520
  • 博客等级: 少校
  • 技术积分: 680
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-22 15:10
文章分类

全部博文(65)

文章存档

2011年(1)

2010年(64)

我的朋友
最近访客

分类: C/C++

2010-06-03 02:18:27

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int count_str (char*);

int main (int argc, char *argv[])
{
    char *str = NULL;
    str = (char *)malloc(sizeof(char) * 100);

    printf("Please input the string you want to count:\n");

    fgets(str, 100,stdin);

    printf("The length of %s is mycount=%d,strlen=%d\n", str, count_str(str), strlen(str));

    return 0;
}

/* 不采用变量, 利用递归的方法 */
int count_str (char *string)
{
     if(*string == '\0')
     {
         return 0;
     }
     else
     {
         return(1 + count_str(++string));
     }
}

 gcc -o strlenstrlen.c
 ./strlen
 Please input the string you want to count:
 this is a
 The length of this is a
 is mycount=16,strlen=16

 

/* 采用指针变量,效率较低 */
int *count_str(char *str)
{
    char *tmp = str;

    while(*str != '\0')
    {
        str++;
    }

    return src-tmp;
}

 

/* 采用int变量, 效率相对比采用指针变量高很多 */
int count_str(char *str)
{
    int len = 0;

    for(; *str; ++len)
    {
        str++;
    }

    return len;
}

int count_str(char *str)
{
    int len = 0;

    for(; *str++ != '\0'; )
    {
        len++;
    }

    return len;
}


/* 采用高效的办法 用unsigned long 变量 */
...待补充
阅读(823) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~