正确的方法来清空一个C字符串 [英] Proper way to empty a C-String

查看:1553
本文介绍了正确的方法来清空一个C字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经工作在C项目,需要我用绳子一大堆乱七八糟左右。通常情况下,我做的节目在C ++中,所以这不仅仅是说的String.Empty()有一点不同。

我不知道什么是空的C.字符串这将是它的正确方法?


缓冲区[80] =你好!世界\\ n;// ...的strcpy(缓冲液,);


解决方案

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

这也将工作:

 缓冲[0] ='\\ 0';

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

  memset的(缓冲,0,strlen的(缓冲));

但这只会调零到第一个NULL字符工作

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

  memset的(缓冲,0,sizeof的(缓冲));

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, "");

解决方案

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));

这篇关于正确的方法来清空一个C字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆