为什么写了个字符串的函数,两个差不多的函数差距怎么就这么大呢?

 

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void substring(char *s,int first,int end) 
{
	char *t=new char[end-first];
	int j=0;
	for(int i=first,j=0;i<end;++i,++j)
		t[j]=s[i];
	t[j] = '\0'; 
	cout<<t;
	delete []t;
}
void substring() 
{ 
    char *s = "Hello world"; 
    char t[10]; 
    int i, j; 
    for (i=2, j=0; i<6; i++, j++) 
        t[j] = s[i]; 
    t[j] = '\0'; 
    cout << "s的子字串[2,6)是" << t<<endl; 
}
int main()
{
	char *a="hello world!";
	substring() ;
	substring(a,2,6);
}

第二个直接运行不出来,郁闷啊,谁能帮忙回答一下啊!!

 

修改了一下,原来是在最后一个字符上出了问题

char* substring(char *s,int first,int end)
{
    char *t=new char[end-first+1];
    int j=0,i=first;
    while(i<end)
        t[j++]=s[i++];
    t[j] = '\0';
    return t;
}

看来还是while比较给力!!

 

相关文章:

  • 2022-12-23
  • 2022-01-31
  • 2022-02-28
  • 2021-12-26
  • 2021-07-05
  • 2022-02-12
  • 2022-12-23
  • 2021-05-04
猜你喜欢
  • 2021-09-15
  • 2021-09-29
  • 2021-11-14
  • 2022-12-23
  • 2021-06-18
  • 2021-05-25
  • 2021-10-08
相关资源
相似解决方案