我剛開始學習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