获取字符串的前n个字符(程序填空)

描述

获取字符串的前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 

输出样例 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;

}

错误原因欢迎各抒己见 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值