求出字符串s中所包含的字符的个数,并作为函数的返回值(要求不使用库函数strlen())。

如题所述

第1个回答  2007-11-30
不使用 strlen()
可以这么做:
#include "Stdio.h"
#include "String.h"
#define N 20
/*上面的20可以自己设,表示a的空间大小.*/
main()
{
int sum=0;
char *str="a"; /*赋初值,否则可能出现错误*/
printf("the words :");
scanf("%s",str);
sum=count(str);
printf("%d",sum);
getch(); /*使窗口停在输出后的窗口,可以看到结果,不然窗口就一闪而过 */
}
count(char *str)
{
int i,n=0;
char a[N];
strcpy(a,str); /*把str的值赋给a*/
for(i=0;a[i]!='\0';i++)
{ n++; }
return n;
}

/*注意,我用win-TC做的,字符必须是连续的,不能有空格。*/
第2个回答  2007-11-30
#include "stdio.h"
#include "conio.h"
main()
{
int len;
char *str[20];
printf("please input a string:\n");
scanf("%s",str);
len=length(str);
printf("the string has %d characters.",len);
getch();
}
length(p)
char *p;
{
int n;
n=0;
while(*p!='\0')
{
n++;
p++;
}
return n;
}
第3个回答  2007-11-30
#include <iostream.h>

int main()
{
char input[99];
int i=0;
memset(input,0,sizeof(input));
cout<<"please input a string:"<<endl;
cin>>input;

for(i =0;input[i]!=0;i++)
{
}

cout<<"the lenth:"<<i<<endl;
return 0;
}
第4个回答  2007-11-30
#include <stdio.h>
main()
{
char s[80];
char *p;
int n=0;
gets(s);
p=s;
while(*p!='\0')
{
n++;
p++;
}
printf("%s the long is %d\n",s,n);
}
第5个回答  2007-11-30
#include <iostream>
using namespace std;
int getLen(char *p)
{
int len=0;
while (*p)
{
++len;
++p;
}
return len;
}
int main()
{
char *p="hehe";
cout << getLen(p);
return 0;
}
相似回答