复制ñ与函数strncpy字符更有效地使用C [英] Copying n chars with strncpy more efficiently in C
本文介绍了复制ñ与函数strncpy字符更有效地使用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道是否有这样做的一个更清洁,更高效的方式如下函数strncpy
考虑最大
量的字符。我觉得像上午矫枉过正。
INT主要(无效)
{ 字符*字符串=你好世界富!
INT最大= 5; 字符*海峡=的malloc(最大+ 1);
如果(STR == NULL)
返回1;
在(string){
INT LEN = strlen的(字符串);
如果(LEN>最大){
函数strncpy(STR,串,最大值);
海峡[MAX] ='\\ 0';
}其他{
函数strncpy(STR,字符串,LEN);
海峡[长度] ='\\ 0';
}
的printf(%S \\ n,STR);
}
返回0;
}
解决方案
我不会用函数strncpy
这在所有。至少如果我理解你想要做什么,我可能会做这样的事情:
的char *复制(字符*输入,为size_t MAX_LEN){
//计算结果的大小 - 指定的最大的小
//和输入字符串的长度。
为size_t的len = MIN(MAX_LEN,strlen的(输入)); //为结果(包括NUL终止符)分配空间。
字符*缓冲=的malloc(LEN + 1); 如果(缓冲液){
//如果分配成功,复制的指定数目
//字符到目的地。
的memcpy(缓冲,输入,LEN);
//和NUL终止的结果。
缓冲[LEN] ='\\ 0';
}
//如果我们复制了字符串,返回它;否则,返回空指针
//指示失败。
返回缓冲区;
}
I'm wondering if there's a cleaner and more efficient way of doing the following strncpy
considering a max
amount of chars. I feel like am overdoing it.
int main(void)
{
char *string = "hello world foo!";
int max = 5;
char *str = malloc (max + 1);
if (str == NULL)
return 1;
if (string) {
int len = strlen (string);
if (len > max) {
strncpy (str, string, max);
str[max] = '\0';
} else {
strncpy (str, string, len);
str[len] = '\0';
}
printf("%s\n", str);
}
return 0;
}
解决方案
I wouldn't use strncpy
for this at all. At least if I understand what you're trying to do, I'd probably do something like this:
char *duplicate(char *input, size_t max_len) {
// compute the size of the result -- the lesser of the specified maximum
// and the length of the input string.
size_t len = min(max_len, strlen(input));
// allocate space for the result (including NUL terminator).
char *buffer = malloc(len+1);
if (buffer) {
// if the allocation succeeded, copy the specified number of
// characters to the destination.
memcpy(buffer, input, len);
// and NUL terminate the result.
buffer[len] = '\0';
}
// if we copied the string, return it; otherwise, return the null pointer
// to indicate failure.
return buffer;
}
这篇关于复制ñ与函数strncpy字符更有效地使用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文