C # language has a lot to learn, here we mainly introduce C # character array conversion, including the introduction of String class System.String provides a void ToCharArray () method and so on.
C # character Array conversions
The String class System.String provides a void ToCharArray () method that enables the conversion of strings to C # character arrays. The following example:
private void TestStringChars() {
string str = "mytest";
char[] chars = str.ToCharArray();
this.textBox1.Text = "";
this.textBox1.AppendText("Length of \"mytest\" is " + str.Length + "\n");
this.textBox1.AppendText("Length of char array is " + chars.Length + "\n");
this.textBox1.AppendText("char[2] = " + chars[2] + "\n");
}
example, the length of the character array to which the transformation was converted and one of its elements were tested, with the following results:
Length of "mytest" is 6
Length of char array is 6
char[2] = t
As you can see, the results are completely correct, which means the conversion was successful. So what about converting a C # character array to a string, in turn?
We can use the constructor of the System.String class to solve this problem. The System.String class has two constructors that are constructed from a character array, i.e. String (char[]) and string[char[], int, int. The latter has two more arguments because you can specify which part of the character array to construct the string. The former, however, constructs the string with all the elements of the character array. Let's take the former as an example and enter the following statement in the Teststringchars () function:
char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
string tstr = new String(tcs);
this.textBox1.AppendText("tstr = \"" + tstr + "\"\n");
Run result input tstr = "Test Me", the test description succeeded.
In fact, many times we need to convert a string into a character array just to get a character in that string. If it's just for this purpose, it doesn't have to be selectmen to do the conversion, we just need to use the System.String [] operator to achieve the goal. Take a look at the example below and add the following name to the Teststringchars () function:
char ch = tstr[3];
this.textBox1.AppendText("\"" + tstr + "\"[3] = " + ch.ToString());
The correct output is "Test Me" [3] = T, tested and the output is correct.