创建我自己的 strlen 和 substring 函数 [英] Create my own strlen and substring functions

查看:34
本文介绍了创建我自己的 strlen 和 substring 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自己的 strlen 和 substr 函数,但有 1 个问题.
例如,假设我有字符串 ABC,我的 strlen 将返回 3,假设我想将此字符串从 0 剪切为 1,它应该返回给我 A,但是如果我将 substr 插入到 a,我会得到一些垃圾值新字符并检查我将收到的长度 14.
这是我的代码:

I am trying to create my own strlen and substr functions and I have 1 problem.
for example, let say I have the string ABC, my strlen will return 3, let say I want to cut this string from 0 to 1 its should return to me A,but I get some trash values, if I insert the substr to a new char and check the length I will recieve 14.
this is my code:

int len(char *w){
    int count=0;
    int i=0;
    while (w[i]!='\0')
    {
        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;
}

我想得到一些评论我做错了什么,谢谢!

I would like to get some comments what I did wrong, Thanks!

推荐答案

改变你的条件循环 for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++) 并且您需要分配大小 +1,因为您必须在字符串末尾添加一个 \0.

Change your condition loop for for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++) and you need to allocate size +1 since you have to add a \0 at the end of the string.

这篇关于创建我自己的 strlen 和 substring 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆