2013-05-02 115 views
-3

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

線索是在問題。取消引用指針以查看它指向的內容,並使用算術將其移至下一個字符。計算你找到的數量,並在找到空字符時停止;或者使用更多的算術來保存必須計數。 – 2013-05-02 16:38:11

+1

您可能想知道下標運算符被定義爲'a [i] == *(a + i)'。所以,如果你可以用下標來做,那麼用指針添加和取消引用就很容易做到。 – 2013-05-02 16:40:13

+0

也可能dup:http://stackoverflow.com/questions/8831323/find-length-of-string-in-c-without-using-strlen – 2013-05-02 16:41:06

回答

1

首先,這不是在2013年學習C++的方法。答案依賴於低級指針操作。在開始學習C++之前,還有很多重要的事情要做。現在,你應該學習字符串,向量,函數,類,而不是關於這些低級細節。

要回答你的問題,你必須知道如何表示字符串。它們表示爲一組字符。在C和C++中,數組沒有內置的長度。所以你必須存儲它或使用一些其他方法來找到長度。字符串的製作方式是,您可以找到長度是他們存儲0作爲數組中的最後一個位置。因此,「你好」將被存儲爲

{'H','e','l','l','o',0} 

要找到你去通過陣列從索引0開始,當你遇到一個0字符值停止長度;

的代碼會是這個樣子

int length(const char* str){ 
    int i = 0; 
    for(; str[i] != 0; i++); 
    return i; 
} 

現在,在C和C++,你可以STR [1]是一樣的*(STR + I); 所以要滿足你的問題,你可以把它寫這樣

int length(const char* str){ 
    int i = 0; 
    for(; *(str + i) != 0; i++); 
    return i; 
} 

現在,而不是使用+我,你可以直接增加STR;

int length(const char* str){ 
    int i = 0; 
    for(; *str++ != 0; i++){; 
    return i; 
} 

現在,在C,值是假的,如果是0,否則它是真實的,所以我們不需要!= 0,所以我們可以寫

int length(const char* str){ 
    int i = 0; 
    for(; *str++; i++){; 
    return i; 
} 
+0

對不起,如果這是過時的方式,但在你的最後2個片段,爲什麼你有一個無與倫比的大括號? – mmmveggies 2015-09-04 00:56:35

4

既然你這樣做是作爲教育的事情,我不會給你答案。但我會在路上幫你一下。

使用char*++運算符檢查終止零\0這將是字符串中的最後一個字符。

0
#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); 
} 
相關問題