简体   繁体   English

在C ++中从具有多个NULL'\\ 0'的函数返回字符串

[英]Returning string from function having multiple NULL '\0' in C++

I am compressing string. 我正在压缩字符串。 And the compressed string sometimes having NULL character inside before the end NULL. 并且压缩的字符串有时在结束NULL之前的内部具有NULL字符。 I want to return the string till the end null.But the compressor function is returning the sting till the occurring of the first NULL. 我想将字符串返回到null结尾,但是压缩器函数将返回字符串直到出现第一个NULL。 I made a question for c before about it. 我之前曾向c提出过一个问题。 But consecutively I need also the solution in C++ now, and in next C#. 但是连续地,我现在还需要C ++和下一个C#中的解决方案。 Please help me.Thanks. 请帮助我。谢谢。

char* compressor(char* str)
    {
      char *compressed_string;
      //After some calculation
      compressed_string="bk`NULL`dk";// at the last here is automatic  an NULL we all know
    return compressed_string;
    }
void main()
   {
    char* str;
    str=compressor("Muhammad Ashikuzzaman");
    printf("Compressed Value = %s",str);

   }

The output is : Compressed Value = bk; 输出为:压缩值= bk; And all other characters from compressor function is not here. 压缩器功能的所有其他字符均不在此处。 Is there any way to show all the string. 有没有办法显示所有字符串。

The fundamental problem that you have is that compression algorithms operate on binary data rather than text. 您遇到的根本问题是压缩算法对二进制数据而不是文本进行操作。 If you compress something, then expect some of the compressed bytes to be zero. 如果压缩某些内容,则预期某些压缩字节为零。 Thus the compressed data cannot be stored in a null-terminated string. 因此,压缩后的数据不能存储在以空值结尾的字符串中。

You need to change your mindset to work with binary data. 您需要改变思维方式以使用二进制数据。

To compress do the following: 要压缩,请执行以下操作:

  1. Convert from text to binary using some well-defined encoding. 使用一些定义明确的编码将文本转换为二进制。 For instance, UTF-8. 例如,UTF-8。 This will yield an array of unsigned char . 这将产生一个unsigned char数组。
  2. Compress the unsigned char , which will again yield an array of unsigned char , but now compressed. 压缩unsigned char ,这将再次产生unsigned char数组,但现在已压缩。

To decompress you just reverse these steps. 要解压缩,只需反转这些步骤。

Since you are writing C++ code you would be well advised to use standard containers. 由于您正在编写C ++代码,因此建议您使用标准容器。 Such as std::string or std::wstring and std::vector<T> . std::stringstd::wstringstd::vector<T>

The exact same principles apply in all languages. 完全相同的原则适用于所有语言。 When you come to code this in C#, you need to convert from text to binary. 当您使用C#编写代码时,需要将文本转换为二进制。 Use Encoding.GetBytes() to do that. 使用Encoding.GetBytes()来做到这一点。 That yields a byte array, byte[] . 产生一个字节数组byte[] Compress that to another byte array. 将其压缩为另一个字节数组。 And so on. 等等。

But you really must first overcome this desire to attempt to store binary data in text data types. 但是您确实必须首先克服这种尝试以文本数据类型存储二进制数据的愿望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM