Viyi.Strings is a .NET library that supports .Net Standard 2.0 and .Net 5. As you can see from the name, the main purpose of this library is to solve some operations on strings and text. In general, the current version of Viyi.Strings provides the following functions:

  • Text-based encoding/decoding, supports Base64 and Hex (hexadecimal) encoding/decoding, but more than that;
  • Provide extension methods for fast processing of empty strings and blank strings;
  • Provides a string case conversion framework, and provides camelCase, PascalCase, kebab-case and snake_case conversion methods by default;
  • It is very convenient to perform 2~36 base conversion between integer and string, even if you only want to use hexadecimal;
  • Expand the analysis of Boolean values, allowing on/off , yes/no , allowing flexible custom conversion;
  • If there are other requirements, please put forward and discuss in Issue
how to install?

The Viyi.Strings library has been published to NuGet and can be quickly installed from NuGet.

Text-based encoding/decoding framework

A text-based encoding/decoding framework is provided under Viyi.Strings.Codec namespace of the Viyi.String library. Under this namespace, not only common encoding/decoding methods such as Base64 and Hex are provided, but also a unified encoding/decoding interface design is provided, which facilitates the unified replacement of encoding/decoding methods in certain scenarios. In addition, this namespace also provides easy-to-use extension methods.

Fast Base64/Hex encoding/decoding

Viyi.Stings.Codec.Base64 namespace byte[] provided EncodeBase64() and DeocdeBase64() series expansion method, can quickly byte[] codec to convert between and Base64 string:

// 随机产生 20 字节数据
byte[] data = new byte[20];
Random r = new Random();
r.NextBytes(data);

string base64;
Console.WriteLine("不加参数:");
Console.WriteLine(base64 = data.EncodeBase64());
// 输出:RdFVrmsY45kkFKkUULem1LfCP6Y=

Compare(data, base64.DecodeBase64());  // 完全匹配

Console.WriteLine("指定行宽为 16:");
Console.WriteLine(base64 = data.EncodeBase64(16));
// 输出:RdFVrmsY45kkFKkU
// 输出:ULem1LfCP6Y=

Compare(data, base64.DecodeBase64());  // 完全匹配

Even if Base64 lacks the last number = , it can be decoded successfully, because the = originally represents empty data.

Console.WriteLine(base64 = data.EncodeBase64());
Compare(data, base64.DecodeBase64());  // 完全匹配

// 根据上面示例,base64 最后一个字符是 = 号,去掉之后再解码
Compare(data, base64.Substring(0, base64.Length - 1).DecodeBase64()); // 完全匹配

The above demonstrates that Base64 encodes/decodes quickly through extension methods. The encoding and decoding according to Hex (hexadecimal) is similar, but the Viyi.Strings.Codec.Hex namespace is required.

Complete Base64/Hex encoding/decoding

The extension method only provides quick encoding/decoding methods byte[] and string If you need more complex encoding / decoding, as to Stream for encoding / decoding, can be used Encoder and Decoder . You can get the preset Base64Codec and HexCodec objects through the Viyi.String.Codec.TextCodec class. They all implement the ITextCodec interface.

  • Use CreateEncoder() create a corresponding encoder object for encoding byte data
  • Use CreateDecoder() create a corresponding decoder object for decoding string data

For example, if you want to convert data.bin into hexadecimal and output it to data_hexdump.txt , you can use this code to complete:

var hexEncoder = TextCodec.Hex.CreateEncoder(
    // 选项属性只读,需要使用建造者模式来构建
    CodecOptions.Create()
        // 配置换行:每行 16 字节,也就是 32 个十六进制字符
        .SetLineWidth(16 * 2)
        .Build()
);

using Stream inStream = File.OpenRead("data.bin");
using StreamWriter writer = new StreamWriter("data_hexdump.txt");
hexEncoder.Encode(writer, inStream);

If the encoding result does not want to be written to a file, but is saved in a string, use StringWriter as the output, or use another overload of Encode

string hex = hexEncoder.Encode(inStream);

For more information about encoding/decoding, you can read: text encoding and decoding (Viyi.Strings.Codec) )

Naming style (case) conversion

In the large environment of multi-terminal, multi-language, and multi-technology joint implementation of application software/services, if you want to keep each part in compliance with their own grammar and data specifications, it is necessary and common to perform different style conversions on naming.

Viyi.Strings provides a framework for naming style conversion in the Viyi.Strings.CaseConverters namespace, and provides conversion tools for camelCase, PascalCase, kebab-case and snake_case by default. These tools all implement the ICaseConverter interface, which is convenient for quick selection or replacement when necessary.

At the same time, in the Viyi.Strings namespace, string is also provided for processing calls. for example:

Console.WriteLine("Hello James Fan".KebabCase());
// 输出:hello-james-fan

If you need to know more about it, you can read: Naming Style Conversion CaseConvert

Empty string and blank string

This part of the function is mainly to expand the string to handle empty strings "" and blank strings (strings containing only blank characters).

For example, if we know that if a string is null , we can change it to the default "default_value" can write:

s = s ?? "default_value";
// 或者 s ??= "default_value";

However, if you want to replace a string when it is an empty string, you need to write like this Viyi.Strgins

// 如果是 null 或空字符串则替换为默认内容
s = string.IsNullOrEmpty(s) ? "default_value" : s;

// 如果仅空白字符串替换为默认内容,null 不变
s = string.IsNullOrWhiteSpace(s) ? "" : s;

But using extensions is much more convenient:

// 如果是 null 或空字符串则替换为默认内容
s = s.EmptyAs("default_value");

// 如果仅空白字符串替换为默认内容,null 和 "" 不变
s = s?.SpacesAs("");

There is no need to use the ternary operator, and it is more concise to use in complex expressions.

In addition, IsEmpty(this string, true) and IsSpaces(this string, true) are also provided to accurately determine that the string is only an empty string and an empty string (exactly null is included).

For more details, please read: empty string and blank string

Parse the boolean

The default Boolean analysis of .Net can only process "true" and "false" , but in actual use, such as on/off , yes/no etc. can also be converted to Boolean data. Viyi.Strings provides multiple ToBoolean() overloads to achieve various requirements, such as

// 如果 s 是 true,返回 true;s 是 false 返回 false;否则返回 null。
s.ToBoolean(true);

// 与第 1 个参数匹配返回 true;与第 2 个参数匹配返回 false;否则返回 null。
s.ToBoolean("yes", "no");

// 在第一个数组中返回 true;在第 2 个数组中返回 false;其它情况返回 null。
s.ToBoolean(new String[] { "yes", "on" }, new String[] { "no", "off" });

// 与第一个参数之后的任意参数匹配,返回第一参数的表示的布尔值,否则返回相反值
s.ToBoolean(false, "no", "off", "false", "down");

For more information, please read: resolves to Boolean type (bool) )

Integer conversion

Viyi.Strings Viyi.Strings.Extensions conversion tool function in the 061a2d49c571a8 namespace, which can convert between strings and int , uint , long , ulong . for example

"3ae".ToInt32(16); // 942
"3ae".ToInt32(16).ToString(8); // 1656
(36 + 35).ToString(36); // 1z

For updated content, please read: integer conversion

Concluding remarks

This is the end of the introduction to Viyi.Strings. Interested friends are welcome to participate in this open source tool library!

The source code is hosted on Gitee: Biancheng/Viyi.String


边城
59.8k 声望29.6k 粉丝

一路从后端走来,终于走在了前端!