正确的方法来清空C字符串(Proper way to empty a C

编程入门 行业动态 更新时间:2024-10-18 22:25:29
正确的方法来清空C字符串(Proper way to empty a C-String)

我一直在用C语言开发一个项目,需要我大量使用字符串。 通常情况下,我使用C ++编程,所以这与仅说string.empty()有点不同。

我想知道在C中清空字符串的正确方法是什么?会是这样吗?

buffer[80] = "Hello World!\n"; // ... strcpy(buffer, "");

I've been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.empty().

I'm wondering what would be the proper way to empty a string in C. Would this be it?

buffer[80] = "Hello World!\n"; // ... strcpy(buffer, "");

最满意答案

这取决于你的意思是“空”。 如果你只是想要一个零长度的字符串,那么你的例子将工作。

这也将起作用:

buffer[0] = '\0';

如果你想把字符串的全部内容清零,你可以这样做:

memset(buffer,0,strlen(buffer));

但是这只会用于调零至第一个NULL字符。

如果字符串是一个静态数组,你可以使用:

memset(buffer,0,sizeof(buffer));

It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.

This will also work:

buffer[0] = '\0';

If you want to zero the entire contents of the string, you can do it this way:

memset(buffer,0,strlen(buffer));

but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use:

memset(buffer,0,sizeof(buffer));

更多推荐

本文发布于:2023-04-28 05:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   方法来   清空   正确   empty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!