我刚开始学习C++。我也想清楚,这不是家庭作业问题,它只是我被困住的东西。计算字符串的长度而不使用标准库函数(如strlen)或索引运算符[]
我在麻省理工学院的网站上接受任务问题,我已经在这里贴上了这个问题;
编写一个返回字符串长度的函数(char *),不包括最终的NULL字符。它不应该使用任何标准库函数。您可以使用算术和取消引用操作符,但不要使用定义操作符([])。
我不知道如何做到这一点,没有数组。
任何帮助表示赞赏!
这是我做过什么:
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int stringlength (char* numptr);
int main()
{
char *mystring;
cout<<"enter the string \n";
cin>>mystring;
cout<<"length is "<<stringlength(mystring);
getch();
}
int stringlength (char* numptr)
{
int count=0;
for(;*numptr<'\0';*numptr++)
{
count++;
}
return(count);
}
This is what i had done previously before I asked u all about the problem.
But this got me an answer of zero.
But if in my function i change *numptr<'\0' to *numptr!= 0, i get the right answer.
Now what i am confused about is, isn't that the null character, so why cant i check for that.
线索是在问题。取消引用指针以查看它指向的内容,并使用算术将其移至下一个字符。计算你找到的数量,并在找到空字符时停止;或者使用更多的算术来保存必须计数。 – 2013-05-02 16:38:11
您可能想知道下标运算符被定义为'a [i] == *(a + i)'。所以,如果你可以用下标来做,那么用指针添加和取消引用就很容易做到。 – 2013-05-02 16:40:13
也可能dup:http://stackoverflow.com/questions/8831323/find-length-of-string-in-c-without-using-strlen – 2013-05-02 16:41:06