在截断方面需要帮助
Need a help on truncating
大家好,
我需要给出一个简单程序的想法。
编写一个将字符串缩短为 n 个字符的函数。如果字符串已经比 n 短,则函数不应更改字符串。假设原型是
void truncate(char *str, int inLen);
简单说明一下..
谢谢
#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] = '[=10=]';
}
return;
}
int main()
{
truncateCharArray(30,'dsd');
return 0;
}
That what I have already tried.
既然你已经尝试了一些你自己的逻辑,那么现在我可以在这里用 c 来解决你的问题
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)
大家好,
我需要给出一个简单程序的想法。
编写一个将字符串缩短为 n 个字符的函数。如果字符串已经比 n 短,则函数不应更改字符串。假设原型是
void truncate(char *str, int inLen);
简单说明一下..
谢谢
#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] = '[=10=]';
}
return;
}
int main()
{
truncateCharArray(30,'dsd');
return 0;
}
That what I have already tried.
既然你已经尝试了一些你自己的逻辑,那么现在我可以在这里用 c 来解决你的问题
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)