C # Common String handling

Source: Internet
Author: User
Tags array to string decimal to binary float number string format

In the process of coding, we often need to handle some strings. For example, some splitting of strings, substitution of characters in strings, and clipping, for example, the need to convert strings into transitions, formatting constraints, and so on. These frequently used methods are sorted as follows:

Convert.ToString (...)

1. Decimal Turn binary

             int d = Ten;  
             Decimal to binary string  
             Console.WriteLine (convert.tostring (d,2));  
            Output: 1010  
2. Decimal turn hexadecimal string

            int d = Ten;
            Decimal hexadecimal string  
            Console.WriteLine (convert.tostring (d,));
            Output: A  
3. Binary string to decimal number

            Binary string decimal number  
            String bin = "1010";  
            Console.WriteLine (Convert.ToInt32 (bin,2));  
            Output: 10  
4. Binary turn hexadecimal

           Binary string hexadecimal number  
            string bin2 = "1010";  
            Console.WriteLine (String. Format ("{0:x}", Convert.ToInt32 (bin2,2)));  
            Output: A  
5.16 Binary Conversion binary system

           Hexadecimal binary string  
           Console.WriteLine (convert.tostring (0xa,2));  
           Output: 1010  
6.16 Decimal digits

            Hexadecimal decimal number  
            Console.WriteLine (convert.tostring (0xa,10));  
            Output: 10  
7. String left complement 0

            int dn=11;
            Console.WriteLine (Convert.ToString (DN, 16). PadLeft (2, ' 0 '));
            Output: 0b
8. String replacement

            string strt = "Hello World";
            STRT = strt. Replace ("L", "L");
            Console.WriteLine ("New string is" + strt);
            Output Result: HeLLo World
9. String clipping

            string strt = "Hello World";
            STRT = strt. Substring (STRT. IndexOf ("E") +1);
            Console.WriteLine ("New2 string is" + strt);
10. String splitting

            String str2= "1,2,3,4.5.6.7";
            String[] STRM=STR2. Split (New char[2]{', ', '. '});
            foreach (string var in strm)
            {
                Console.Write (var+ "");
            }
            The output results are:
            1 2 3 4 5 6 7  
11. String split, more complex, with a word split

            String str3 = "Hellomrzhanghellomisslihellomrzhao";
            string[] StrName = System.Text.RegularExpressions.Regex.Split (STR3, "Hello", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            foreach (string var in strName)
            {
                Console.Write (var + "");
            }
            Output result: <pre name= "code" class= "CSharp" >            mrzhang missli mrzhao  

12. String replacement, more complex, can replace multiple

        
           string s = Regex.Replace ("Abracadabra", "Abra", "zzzz");
<pre name= "code" class= "CSharp" >           console.write (s);
Result: zzzzcadzzzz

13. Remove string spaces

          String   tt= "AAA"; 
          Tt=tt. Trim ();      Go to the TT=TT function of the string and tail space
          . TrimEnd ();   Remove the trailing space tt=tt of the string
          . TrimStart (); Remove the first space of the string
14. String-turn character array, Method 1

            String str1 = "Fafaaf";
            String str2;
            Copy of the string, using a static method string. Copy (string source)  
            str2 = string. Copy (STR1);
            The method of converting a string to a character array is 1:str. CopyTo (int sourceindex, char[] destination, int destinationindex, int count)  
            char[] Chaarr = {' A ', ' 2 ', ' 3 ', ' 4 ', ' 5 ' , ' 6 '};
            Str2. CopyTo (0, Chaarr, 0, 6);
            Console.WriteLine (str2);
            foreach (char mychar in Chaarr)
            {
                console.write (MyChar);
            }
            Console.WriteLine ();
15. String-turn character array, Method 2
            The method of converting a string to a character array 2:tochararray ()  
            char[] charArr2 = new Char[6];
            CHARARR2 = str2. ToCharArray ();
            foreach (char mychar1 in charArr2)
            {
                console.write (MYCHAR1);
            }
16. String-turn character array, Method 3 GetBytes ()

        private static void Teststringbytes ()
        {
            string s = "C # language";
            Byte[] B1 = System.Text.Encoding.Default.GetBytes (s);
            byte[] B2 = System.Text.Encoding.Unicode.GetBytes (s);
            string T1 = "", t2 = "";
            foreach (Byte b in B1)
            {
                T1 + = b.tostring ("") + "";
            }
            Console.WriteLine ("1th Encoding" +t1.) ToString ());
            foreach (Byte b in B2)
            {
                T2 + = b.tostring ("") + "";
            }
            Console.WriteLine ("2nd encoding" + T2.) ToString ());
            Console.WriteLine ();
        
17. Convert character array to string

           Byte[] bs = {The same, the 102
           , the string ss = System.Text.Encoding.ASCII.GetString (BS);
           This.textBox1.AppendText ("The string is:" + SS + "\ n"); 
           Console.WriteLine (ss);
          The output result is: abcdef
18. The scientific counting method translates into the ordinary counting Method 1

          Double A = 7E-7;
          String B = a.tostring ("0.0000000000");//parentheses inside the string format
          Console.WriteLine ("New is" +b);
19. The scientific counting method translates into the ordinary counting Method 2

         1. The string value contains scientific notation such as e, such as 12e-2,///need to be converted to ordinary numerical 0.12,
         //2. The conversion function is as follows:
         //code as follows:       private Decimal Changedatatod (String strdata)       {            Decimal ddata = 0.0M;            if (Strdata.contains ("E"))            {                  ddata = Convert.todecimal (Decimal.Parse (strdata.tostring ()), System.Globalization.NumberStyles.Float));            }            return ddata;      }      3. Call directly Changedatad (strtex//t)
        //4. After the run is 0.12.          
20. String conversion to numeric type, Parse method

String data converted to numeric type using the Pares () method

        The string is converted to integral with Int. Parse ()
        string str= ";
        " int Number=int. Parse (str);
        The string is converted to a double-precision floating-point double  . Parse () string
        string str= ";
        " Double number =double. Parse (str);
        The string is converted to single-precision floating-point  float. Parse (String)
        string str= ";
        " Float number=float. Parse (str);

        Not knowing. Strings can be converted to numeric data, and only strings that can be represented as numbers can be converted, such as the name "John", converted to a number without an acceptable expression, and cannot be converted
        //Note that the parameters in the Pares () bracket can only be strings. cannot be a different data type.
        Attention
        Int. TryParse (str) meaning an attempt to convert a non-int type of data to an int type data, the conversion succeeds returning true, otherwise it returns false

21. A comparison of parse and convert

The difference is:

                  Convert requires a parameter of type obj
                  Parse requires a parameter string of type















Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.