我刚开始学习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.
答案 0 :(得分:4)
因为你这是一个教育性的事情,我不会给你答案。但是我会在路上帮你一点。
使用char*
和++
运算符检查终止为零\0
这将是字符串中的最后一个字符。
答案 1 :(得分: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,则值为false,否则为true,因此我们不需要!= 0,所以我们可以写
int length(const char* str){
int i = 0;
for(; *str++; i++){;
return i;
}
答案 2 :(得分: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);
}