创建我自己的strlen和子字符串函数
Create my own strlen and substring functions
我正在尝试创建自己的strlen和substr函数,但我有一个问题
例如,假设我有字符串ABC,我的strlen将返回3,假设我想将此字符串从0剪切到1,它应该返回A,但我得到了一些垃圾值,如果我将子字符串插入到一个新的字符并检查长度,我将获得14。
这是我的代码:
int len(char *w){
int count=0;
int i=0;
while (w[i]!=' ')
{
count++;
i++;
}
//cout<<"Length of word is:"<<count<<"n";
return count;
}
char *subs(char *w,int s,int e){
int i,j;
int size=0;size=(e-s);
//cout<<"new size is:"<<size<<"n";
char *newW=new char[size];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
return newW;
}
int main(){
char* x="ABC";
//int v=len(x);
//cout<<v;
char *n=subs(x,0,1);
cout << len(n);
for(int g=0;g<len(n);g++)
//cout<<n[g];
return 0;
}
我想得到一些评论我做错了什么,谢谢!
更改for(i = 0, j = s ; j < e && w[j] != ' '; i++, j++)
的条件循环,您需要分配大小+1,因为您必须在字符串末尾添加\0。
子字符串应以"\0"结尾,数组大小应加一。这是代码:
char *subs(char *w,int s,int e){
int i,j;
int size=0;size=(e-s);
//cout<<"new size is:"<<size<<"n";
char *newW=new char[size + 1];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
newW[i] = ' ';
return newW;
}
相关文章:
- 字符串函数在目标C++上运行时C++返回空
- 字符串函数返回奇怪的值
- 这里的字符串函数是什么意思
- 在字符串函数中抛出'char const*'实例后调用的终止
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 从C++为字符串函数设置_ENV
- 来自 2D 数组的字符串函数
- 返回最长的公共子字符串函数 c ++
- 使用getline和字符串函数C++程序中的分段错误
- 在字符串函数的指针中返回地址
- 字符串函数:strcat()
- 这个子字符串函数有什么问题
- 字符串函数不返回字符串? C++
- 使用向量和字符串函数返回字符串
- 尝试修复一个字符串函数,该函数采用字符串并通过替换一些单词来更改它
- 逐字读取字符数组,无需字符串函数
- 我从我的字符串函数返回到主函数
- 为什么我不能从字符串函数返回字符串数组?
- 如何在不使用字符串函数的情况下在char数组中找到字符串?(C )
- 带有 #include< iostream.h> 的程序允许使用 strlen() 等字符串函数。为什么?