Type conversion in C #: conversion between string and character array () ========================================================== ========================== Author: hphubei (http://hphubei.itpub.net)
Posted:
Classification: ASP. NET skills
Source: http://hphubei.itpub.net/post/2868/304735
--------------------------------------------------------------- 5. Conversion between string and character array
The string class system. String provides a void tochararray () method, which can be used to convert strings to character arrays. For example:
Private void teststringchars (){
String STR = "mytest ";
Char [] chars = Str. tochararray ();
This. textbox1.text = "";
This. textbox1.appendtext ("length of" mytest "is" + Str. Length + "");
This. textbox1.appendtext ("length of char array is" + chars. Length + "");
This. textbox1.appendtext ("char [2] =" + chars [2] + "");
}
In this example, the length of the converted character array and one of its elements are tested. The results are as follows:
Length of "mytest" is 6
Length of char array is 6
Char [2] = T
It can be seen that the result is completely correct, which indicates that the conversion is successful. In turn, what should we do if we want to convert character arrays into strings?
We can use the constructor of the system. string class to solve this problem. The system. string class has two constructor functions constructed through character arrays, namely, string (char []) and string [char [], Int, INT ). The latter has two more parameters because it can specify which part of the character array is used to construct the string. The former uses all elements of the character array to construct a string. For example, in the teststringchars () function, enter the following statement:
Char [] TCS = {'T', 'E','s ', 't', '', 'M', 'E '};
String tstr = new string (TCS );
This. textbox1.appendtext ("tstr =" "+ tstr + """);
Enter tstr = "test me" in the running result. The test indicates that the conversion is successful.
In fact, many times we need to convert a string into a character array to obtain a character in the string. For this purpose alone, we do not need to perform conversion by using the [] Operator of system. String. Refer to the following example and add the following language name to the teststringchars () function:
Char CH = tstr [3];
This. textbox1.appendtext ("+ tstr +" "[3] =" + CH. tostring ());
The correct output is "test me" [3] = T. After testing, the output is correct.