相当无语:字符串的疑惑

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

 

#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比较给力!!

 

posted @ 2010-10-28 09:28  hailong  阅读(339)  评论(0编辑  收藏  举报