C# basics (strings and methods)

1), immutability of strings

When you reassign a value to a string, the old value is not destroyed, but a new space is created to store the new value.

When the program ends, the GC scans the entire memory. If it finds that some space is not pointed to, it will be destroyed immediately.

2). We can regard strings as arrays of read-only char type.

ToCharArray(); Convert string to char array

new string(char[] chs); can convert char array char array into string

​
 public class Program
    {
        public static void Main()
        {
            string s = "CGW";
            char[] ch = s.ToCharArray();
            ch[0] = 'A';
            s = new string(ch);//最后s为"AGW"
            Console.ReadKey();
        }

    }

​

Various methods provided by strings

1. Length: Get the number of characters in the current string

 public class Program
    {
        public static void Main()
        {
            string s = "获取该字段的长度";
            Console.WriteLine(s.Length);//输出为8
            Console.ReadKey();
        }

    }

2. ToUpper(): Convert the string to uppercase; ToLower(): Convert the string to lowercase

    public class Program
    {
        public static void Main()
        {
            string s = "c#";      
            Console.WriteLine(s.ToUpper());//转换成大写
            Console.WriteLine(s.ToLower());//转换成小写
            Console.ReadKey();
        }

    }

3. Equals(str,StringComparison.OrdinalIgnoreCase): Compares two strings (ignoring case)

    public class Program
    {
        public static void Main()
        {
            string s = "c#";
            string s1 = "C#";
            Console.WriteLine(s.Equals(s1,StringComparison.OrdinalIgnoreCase));
            //最后输出turn
            Console.ReadKey();
        }
    }

 4. Split(); splits the string and returns an array of string type

  string [] names = { "1" , "2" , "3" };
  string strNames = string.Join("|", names);
  Console.WriteLine(strNames);
  //最后为1|2|3
  Console.ReadKey();

5. Substring(): intercept the string and include the position to be intercepted when intercepting

  string s = "abcde";
  //第一个参数从指定的位置截取,包含指定的位置,第二个参数截取的长度
  s = s.Substring(1, 2);
  //从指定的位置截取到末尾,包含指定的位置
  s = s.Substring(0);
  Console.WriteLine(s);
  Console.ReadKey();

6. IndexOf(): Determine the position where a certain string first appears in the string. If not, return -1;

     LastIndexOf(): Determines the last occurrence of a certain string in the string. If not, returns -1

  string s = "12341";
  //1第一次出现的地方
  int i = s.IndexOf("1");
  //l最后一次出现的位置
  int j = s.LastIndexOf("l");
  Console.WriteLine(s); 
  Console.ReadKey();

Guess you like

Origin blog.csdn.net/m0_55074196/article/details/126709753