-3

我刚刚开始学习c++。我还想澄清一下,这不是作业问题,它只是我坚持的问题。

我在麻省理工学院网站上查看作业问题,我已将问题粘贴在这里;

编写一个返回字符串长度(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.
4

3 回答 3

4

既然你这样做是为了教育,我不会给你答案。但我会在路上帮助你一点。

使用 achar*++运算符检查是否以零结尾,\0这将是字符串中的最后一个字符。

于 2013-05-02T16:39:29.427 回答
1

首先,这不是 2013 年学习 C++ 的方式。答案依赖于低级指针操作。在达到这一点之前,还有很多关于 C++ 的重要知识需要了解。现在,您应该学习字符串、向量、函数、类,而不是这些低级细节。

要回答您的问题,您必须知道字符串是如何表示的。它们表示为一个字符数组。在 C 和 C++ 中,数组没有内置长度。因此,您必须存储它或使用其他一些方法来查找长度。字符串的制作方式是您可以找到长度,它们存储一个 0,作为数组中的最后一个位置。因此“Hello”将被存储为

{'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[i] 与 *(str + i); 相同。所以为了满足你的问题,你可以这样写

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

现在,您可以直接递增 str,而不是使用 + i;

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;
} 
于 2013-05-02T16:53:45.207 回答
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);
 }
于 2013-05-07T17:35:31.143 回答