描述
获取字符串的前n个字符(默认的函数参数)
#include <iostream>
#include <cstring>//获取字符串的前n个字符,n默认值为1
char * left(______________________________) ;int main() {
char s[]="fdsfdsfds234234543543scfxzDSGFD*&ASGFwR12%$^";
std::cout<<left(s)<<':'<<left(s,10)<<':'<<left(s,100)<<std::endl;
return 0;
}char *left(const char *s,int n) {
________________________________________
________________________________________
________________________________________
________________________________________
________________________________________
________________________________________
________________________________________
________________________________________
________________________________________
}输入
无
输出
字符串"fdsfdsfds234234543543scfxzDSGFD*&ASGFwR12%$^"的前1、10、100个字符。
输入样例 1
目录
无输出样例 1
f:fdsfdsfds2:fdsfdsfds234234543543scfxzDSGFD*&ASGFwR12%$^
#include <iostream>
#include <cstring>
//获取字符串的前n个字符,n默认值为1
char* left(const char* s, int n);
char* left(char* s);
int main() {
char s[] = "fdsfdsfds234234543543scfxzDSGFD*&ASGFwR12%$^";
std::cout << left(s) << ':' << left(s, 10) << ':' << left(s, 100) << std::endl;
return 0;
}
第一种:
char* left(const char* s, int n) {
char* p = new char[n+1];
int i = 0;
while (s[i] != '\0' && i < n) {
p[i] = s[i];
i++;
}
p[i] = '\0';
return p;
}
比较浪费存储空间。
第二种:
char * left2(const char *str,int n)
{
if(n<0)
n=0;
int len=strlen(str);
n=(n<len)?n:len;
char *p =new char [n+1];
int i;
for(i=0;i<n&&str[i];i++)
p[i]=str[i];
while(i<=n)
p[i++]='\0';
return p;
}
这种方法确保new分配的空间不会多于存储字符串所需要的空间。但是该方法需要调用strlen(),因此程序更长,运行速度将降低,同时还必须包含头文件cstring,或string.h。
第三种:
char * left3(const char *str,int n)
{
int m=0;
while(m<n&&str[m])
m++;
char *p =new char [m+1];
int i;
for(i=0;i<m&&str[i];i++)
p[i]=str[i];
while(i<=m)
p[i++]='\0';
return p;
}
char* left(char* s) {
return left(s, 1);
}
错误示范:
char* left(const char* s, int n) {
char res[100];
char* p = res;
int i = 0;
while (s[i] != '\0' && i < n) {
res[i] = s[i];
i++;
}
res[i] = '\0';
return p;
}
错误原因欢迎各抒己见