2013-05-02 50 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); 
} 
相关问题