需要帮助截断[关闭]

问题描述 投票:-3回答:2

大家好,

我需要对一个简单的程序提出一个想法。

编写一个将字符串缩短为n个字符的函数。如果字符串已经短于n,则该函数不应更改字符串。假设原型是

void truncate(char *str, int inLen);

只是给出一个简单的解释..

谢谢

truncate
2个回答
0
投票

既然你已经尝试过自己的一些逻辑,那么现在我可以在这里试试你的问题

void truncate(char *str, int inLen){
    int len=strlen(str);
    char *newstr;
    newstr=(char *)malloc(inLen*sizeof(char));
    if(inLen>len)
        strcpy(newstr,str);
    else{
        strncpy(newstr,str,inLen);
    }
    printf("%s",newstr);
}

这里的C ++解决方案:

#include<iostream>
#include<string.h>
using namespace std;

void truncate(char *str, int inLen){
    int len=strlen(str);
    char *newstr=new char[inLen];
    if(inLen>len)
        strcpy(newstr,str);
    else{
        strncpy(newstr,str,inLen);
    }
    cout<<newstr;
}
int main()
{
char str[100];
int inLen;
cin>>inLen;
cin>>str;
truncate(str,inLen);
return 0;
}

Python在这里:

string=input("Enter string")
inLen=int(input("Enter trim length"))
newstring=string[0:inLen]
print(newstring)

0
投票
    #include<iostream>
using namespace std;
#include<string.h>

void truncateCharArray(int maxLength , char * inLen )
{
if ((0 == inLen) || !(0 < maxLength))
return;
cout<<"To my eye, this is confusing. Why not simply"<<endl;

if (inLen == NULL || maxLength <= 0)
return;
if (maxLength < strlen(inLen))
cout<<"What if maxLength is equal to the length of buffer?"<<endl;
{
inLen[maxLength] = '\0';
}
return;
}

int main()
{
    truncateCharArray(30,'dsd');
    return 0;
}


That what I have already tried.
© www.soinside.com 2019 - 2024. All rights reserved.