2023/10/30–C#–Immutable strings, string API, use of StringBuilder class, formatted strings, template strings…

1. Create and add arrays

 Array intArray = Array.CreateInstance(typeof(int), 5);
 for (int i = 0; i < intArray.Length; i + + )
 {
     intArray.SetValue(i + 1, i);
 }

Judge the elements in the array based on IndexOf:

If there is this element, the index position of the element is displayed; if there is no such element, -1 is returned;

 Console.WriteLine(Array.IndexOf(intArray, 1)); // 0
 Console.WriteLine(Array.IndexOf(intArray, 0, intArray.Length)); // -1

2. Immutable string

Meaning: string reference type, the string type represents a sequence of zero or more Unicode characters,
string is an alias for String in the .NET Framework.

Immutable string memory is immutable

string str = “123”;
str = “666”; // There is no overwriting, but the pointer pointing has changed, and no one uses 123.

Example comparison: Urban management collects dogs. Dogs must be kept on a leash, otherwise they will be deemed ownerless and will be taken away directly.

String concatenation:

string str1 = "456";
Console.WriteLine(str + str1);

Method to create string:

Method 1 Literal creation of string
 string str3 = "abc";
  string str4 = @"abc";
  Console.WriteLine(str3 + str4);
Method 2 Create a string through a single character array
 char[] charArray = new char[5] { 'a', 'b', 'c', 'd', 'f' };
 string str5 = new string(charArray);
 Console.WriteLine(str5);

Method 3 format string

Format

 string str6 = string.Format("123", "a");
  Console.WriteLine(str6);

// The essence of a string is also a collection of single characters
//Immutable string is essentially a collection of immutable single characters

Two traversal methods:
 string str7 = "abcdgbhj123";
 // Traverse the string
 foreach (char c in str7)
 {
     Console.WriteLine(c);
 }

 for (int i = 0; i < str7.Length; i + + )
 {
     Console.WriteLine(str7[i]);
 }

Revise
// Immutable string length, element type, immutable, variable content. Example:

char[] charArray1 = new char[2] { '1', '2' };
charArray1[0] = 'a';

3. Commonly used string API

1.Length gets the length of the string, that is, the number of characters in the string.
2.IndexOf returns an integer to get the position of the first occurrence of the specified string in the original string.

 int indexCharNumber = str7.IndexOf('a');
  Console.WriteLine(indexCharNumber);

Tips: Learn to check the properties of the small wrench and the small square method
3.LastlndexOf returns an integer to get the position of the last occurrence of the specified string in the original string.
4. StartsWith returns a Boolean value to determine whether a string begins with the specified string.
5. EndsWith returns a Boolean value to determine whether a string ends with the specified string.
6. ToLower returns a new string, converting the uppercase letters in the string to lowercase letters.

 string str8 = "ABC";
 string toLowerStr = str8.ToLower();
 Console.WriteLine(toLowerStr); // abc


7. ToUpper returns a new string, converting the lowercase letters in the string to uppercase letters.
8. Trim returns a new string. Without any parameters, it means to delete the spaces before and after the original string.

//Trim removes spaces on both sides; prefixes and suffixes;
string str9 = "admin root";
string TrimStr = str9.Trim();
Console.WriteLine(TrimStr); //admin root cannot remove the spaces in the middle

9. Remove returns a new string, removing the string at the specified position in the string.

 // Remove deletes the index value 0 and deletes four 4s (truncation length);
  string removeStr = str9.Remove(0, 4);
  Console.WriteLine(removeStr);

10. TrimStart returns a new string, removing the spaces on the left side of the string.
11. TrimEnd returns a new string with the spaces on the right side removed from the string.
12. PadLeft returns a new string, padding spaces from the left side of the string up to the specified
String length.
13. PadRight returns a new string, padding spaces from the right side of the string to the specified
String length.
14. Substring returns a new string, used to intercept the specified string.

//Substring is intercepted starting from the position with index value 2, and all subsequent
string subStr = str9.Substring(2);
//Stay 0-4
string subStr1 = str9.Substring(0, 4);
Console.WriteLine(subStr);
Console.WriteLine(subStr1);

15. Insert returns a new string, inserting a string into another string at the specified index.

 // Insert insertion position index value 4 Add ZZZ
  string insertStr = str9.Insert(4, "zzz");
  Console.WriteLine(insertStr);

16.concat

//Can only directly cw output Concat
Console.WriteLine(str9.Concat("abc"));
//System.Linq.Enumerable + <ConcatIterator>d__59`1[System.Char]

// spliced two
string ConcatStr = string.Concat("aaa", "ccb");
Console.WriteLine(ConcatStr); // aaaccb

17.contains

 // Contains contains bool type suitable for login and registration for judgment.
 bool ContainsStr = str9.Contains("abc");
 Console.WriteLine(ContainsStr);

18.IsNullOrEmpty

 // Determine whether null or empty string
 string.IsNullOrEmpty(str9);

 if (str9 == null || str9 == "")
 {
     Console.WriteLine("The string is illegal!");
 }
 if (str9 == null || str9 == "" || string.IsNullOrEmpty(str9))
 {
     Console.WriteLine("The string is illegal!");
 }

19. char[] charArray = str.ToCharArray();

 //ToCharArray The following is a demonstration of the principle
 string str10 = "abc,def";
 //char[] charArray1 = str10.ToCharArray();
 char[] charArray2 = new char[str10.Length];

 for (int i = 0; i < str10.Length; i + + )
 {
     charArray2[i] = str10[i];
 }

20.str1.Split(‘,’)

 //Split splits the string according to *** Commonly used query strings
   string[] stringArray = str10.Split(',');
   foreach (var item in stringArray)
   {
       Console.WriteLine(item);
   }
   //abc
   // def

   // URL example:
   string str11 = @"https://mbd.baidu.com";
   string[] baiduStr = str11.Split('.');
   foreach (var item in baiduStr)
   {
       Console.WriteLine(item);
   }
   Console.WriteLine(baiduStr[1]);

4.Usage of StringBuilder class

Features:
1. You can define variable strings to add strings
2. Can be used for high-frequency string splicing
3. For ordinary splicing, you can use string formatting

Common methods are as follows:
Append at the end
Insert inserts the specified string at the specified position
Remove removes the specified string

Tips: Double quotes only represent: immutable string splicing

string str12 = "123";
string str13 = "456";
string str14 = "";
Console.WriteLine(str12 + str13 + str14); //123456

//Initialize StringBuilder Operation:

StringBuilder stringBuilder = new StringBuilder();

 // Equivalent to "" + "123"
  stringBuilder.Append(str12);
  // Equivalent to "" + "456"
  stringBuilder.Append(str13);
  Console.WriteLine(stringBuilder); // 123456

Insert usage in StringBuilder:

 stringBuilder.Insert(0, str12, 2); // 2 appended twice
 Console.WriteLine(stringBuilder); // 1231 23123456

Remove usage in StringBuilder:

 stringBuilder.Remove(0, 4);
  Console.WriteLine(stringBuilder); // 23123456

Clear usage in StringBuilder:

 stringBuilder.Clear();
 Console.WriteLine(stringBuilder); // Empty

5. Format string

 int a = 321;
 string name = "Qiang Qiang! Keli appears...";
 Console.WriteLine("{0}! It's opening{1}", name, a); //Clang! Keli appears...! Opening 321

 // Use { } to represent it, fill in the placeholder { } with the corresponding number inside { }
 Console.WriteLine("The current output value is {0}", a); // The current output value is 321
 //Format string
 string newStr = string.Format("The current output value is {0}", a);
 Console.WriteLine(newStr); //The current output value is 321

Some other ways of writing:

// format
int j = 12345;
string formatStr = string.Format("{0}", j);
Console.WriteLine(formatStr); // 12345
string formatStr1 = string.Format("{0:C}", j);
Console.WriteLine(formatStr1); //¥12,345.00
//You can also write it directly in cw
Console.WriteLine("{0:C}", j); //¥12,345.00
Console.WriteLine("{0:D}", j); //12345
Console.WriteLine("{0:E}", j); //1.234500E + 004
Console.WriteLine("{0:F}", j); //12345.00
Console.WriteLine("{0:G}", j); //12345
Console.WriteLine("{0:N}", j); //12,345.00

Console.WriteLine(DateTime.Now); // 2023/10/30 16:40:51 object
//Format string
Console.WriteLine("{0}", DateTime.Now); // 2023/10/30 16:40:51 string
Console.WriteLine("{0:D}", DateTime.Now); // October 30, 2023
Console.WriteLine("{0:y}", DateTime.Now); // October 2023

6. Template string

 string name1 = "Coke";
 int age1 = 22;
 Console.WriteLine($"{name1} is {age1} years old this year!");

If you are not familiar with it, you can learn from the js template string in the front end!

int a = 10;
int b = 2;

//Template string $”{Variable 1},{Variable 2}”

 Console.WriteLine($"The current output value is {a}");
  Console.WriteLine($"The current output value is {a}, the current output value is {b}");
  Console.WriteLine($"The current output value is {a + b}, the current output value is {b - a}");
  Console.WriteLine($"The current output value is {a > b}, the current output value is {b == a}");
  Console.WriteLine($"The current output value is {(a > b ? a : b)}");
  Console.WriteLine($"The current output value is {Sum(10,20)}");