首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++字符串截取的有关问题

2014-06-04 
C++字符串截取的问题//字符串截取#include#include#include#include

C++字符串截取的问题
//字符串截取
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>

using namespace std;

//--截取最后三个字符
char * getLastThree(char * str){
int len=strlen(str);
char last[3];
last[0]=str[len-3];
last[1]=str[len-2];
last[2]=str[len-1];
printf("%s\n",last);
return last;
}



void main(){
char * str="Hello string.asd";
cout<<str<<endl;
getLastThree(str);
system("pause");
}

-----------------------------输出结果----------------
Hello string.asd
asd?
请按任意键继续. . .
----------------------------------------------------
为什么不正确呢?(正确的应该是asd)

如果将上面的代码略作修改:
//字符串截取
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>

using namespace std;

//--截取最后三个字符
char * getLastThree(char * str){
int len=strlen(str);
char last[3];
last[0]=str[len-3];
last[1]=str[len-2];
last[2]=str[len-1];
//printf("%s\n",last);
return last;
}



void main(){
char * str="Hello string.asd";
cout<<str<<endl;
str=getLastThree(str);
cout<<str<<endl;
system("pause");
}
---------------------------------结果输出---------------------
Hello string.asd
H

热点排行