2012-12-11 69 views
6
int count(string s){ 
    if(s == "") 
     return 0; 
    if(s.length == 1) 
     return 1; 
    return 1 + count() //This is what I can't figure out. How to traverse the string. 
    //I just need a hint, not a full on answer. 
} 

我不知道如何遍歷字符串。嘗試確定在C++中使用遞歸的字符串的長度

+2

提示:字符串的大小是1 +刪除第一個(或最後一個)字符的字符串的大小。空字符串的大小爲零。 – zackg

+0

聽起來像作業給我..現在你可能想要在第二行最後一行:return 1 + count(s.substr(0,s.length() - 1)); – Nils

+1

是的,它是功課。沒什麼特別的,但是它讓我很好。 –

回答

10

提示:在遞歸中使用substr()

此外,你有兩個基本情況。其中之一有三個問題:

  1. 它有一個語法錯誤;
  2. 它依賴於能夠計算字符串的長度(這是你的函數應該做的);
  3. 這是沒有必要的,因爲你有其他的基本情況。
+0

我會給這個鏡頭,謝謝! –

+0

我把兩個基本情況,因爲他們說如果字符串是空的返回0,然後我把長度== 1的基本情況,如果它是> 0。 –

+1

@ user1893303你可以使用0作爲你的基本情況。 –

1

如果你的目的是遍歷一個字符串,我建議使用迭代器(見std::string::begin)。

template<typename It> 
int count(It const begin, It const end) 
{ 
    return (begin != end ? count(begin + 1, end) + 1 : 0); 
} 

int count(std::string const& s) 
{ 
    return count(s.begin(), s.end()); 
} 
+1

這是如何使用遞歸? –

+1

@JanDvorak:如果函數的參數是一個迭代器(以及「結束」迭代器),那麼它是遞歸的。 –

1

也許你會想要使用substr

+0

工作就像一個魅力。謝謝 –

3

我不認爲你的例子有任何意義,你使用length已經返回計算中的長度。如果我是你的導師,我不會接受這是一個有效的解決方案。

您可能需要使用const char*

int count(const char* s){ 
    if(*s == '\0') 
     return 0; 
    return 1 + count(s + 1); 
} 
+1

你不需要_need_'const char *',甚至不需要'char *'。 –

+1

問題不在於字符串知道它的長度,而在於OP使用它作爲基本情況。 – irrelephant

+0

從其他例子我發現他們都使用字符,但問題的要求是使用字符串數據類型。我知道它是愚蠢的計數遞歸的長度,當所有你必須是使用length()函數,但我認爲教授希望我們至少經歷字符串遞歸。 –

0

我知道你想要一個C++的解決方案,但仍。有時C比C++更好。

 
int count(const char *s) 
{ 
    if(*s == 0) 
    return 0; 
    else return 1 + count(++s); 
}; 

以count(str.c_str())調用。

0
#include<stdio.h> 
    main(){ 
    char str1[100]; 
    gets(str1); 
    int i=0;i=len(str1,i);printf(" \nlength of string is %d",i); 
    } 
    int len(char s1[],int i) { 
    printf("\n%c",s1[i]); 
    int sum=0,count =1; 
    if(s1[i] == '\0') return 0; 
    else 
    return (count += len(s1,++i)); 
    }