C # string manipulation, transfer from Han Guanlong blog

Source: Internet
Author: User

1.1 String case
Method prototypes
String <strname>.  ToUpper (); Returns the uppercase form of a string conversion
String <strname>.  ToLower (); Returns the lowercase form of a string conversion
For example, when a user enters a user name, it may be confusing in case of input, but we can convert (convert all to uppercase or all to lowercase),
Enable users to log on successfully
Console.Write ("Please enter your user name:");
Convert all to Uppercase
String username = Console.ReadLine ();
String usernameupper = Username. ToUpper ();
Convert all to lowercase
String usernamelower = Username. ToLower ();
Console.WriteLine ("Uppercase is: {0}, lowercase is: {1}", Usernameupper, Usernamelower);

1.2 Remove the specified characters
Trim removes the first and last occurrences of a specified set of characters
Method prototypes
(1) string <strname>.      Trim (); Remove the leading and trailing spaces
String str = "Han Guanlong";
string firstendnullstr = str. Trim ();
Console.WriteLine (Firstendnullstr.   Length); Output Information: 3
(2) string <strname>.   Trim (New char[]{' <char> '}); Removes the specified character (must be the end-to-end character)
String str = "Han Guanlong han";
string firstendnullstr = str. Trim (new char[] {' Korea '});
Console.WriteLine (FIRSTENDNULLSTR); Output information: Ying Long
TrimStart removes the beginning match for a specified set of characters
Method prototypes
(1) string <strname>. TrimStart (); Remove whitespace from the beginning
String str = "Han Guanlong";
string firstendnullstr = str. TrimStart ();
Console.WriteLine (Firstendnullstr.  Length); Output Information: 4
(2) string <strname>. TrimStart (New char[]{' <char> '); Removes the specified character from the beginning
String str = "Han Guanlong han";
string firstendnullstr = str. TrimStart (new char[] {' Korea '});
Console.WriteLine (FIRSTENDNULLSTR); Output information: Ying Long Han
TRIMEND removes the specified end of a specified set of characters
Method prototypes
(1) string <strname>.   TrimEnd (); Remove the trailing space
String str = "Han Guanlong";
string firstendnullstr = str. TrimEnd ();
Console.WriteLine (Firstendnullstr.  Length); Output Information: 4
(2) string <strname>. TrimEnd (New char[]{' <char> ');
String str = "Han Guanlong han";
string firstendnullstr = str. TrimEnd (new char[] {' Korea '});
Console.WriteLine (FIRSTENDNULLSTR); Output information: Han Guanlong

1.3 Comparison of strings
Compare () method
Method prototypes
(1) int Compare (string,string); Comparison of two String objects
int Strcompare=string.compare ("SFSFSF", "SFSFSF"); Output information: 0
(2) int Compare (String,string,boolean)//Compare two string objects, whether or not case is ignored
int int dou = String.Compare ("SDSSD", "SDSSD", true); Output information: 0
(3) int Compare (String,string,stringcomparison)//parameter specifies whether the comparison uses the current culture or the invariant culture.
Whether to consider or ignore case, whether to use a word collation or an ordinal sort rule.
int dou = String.Compare ("DSDSSDD", "DSDSSDD", stringcomparison.ordinalignorecase); Output Information 0
Compare by dictionary sort
If STRA&GT;STRB, the value returned is greater than 0
If STRA=STRB, the returned value is equal to 0
If STRA&LT;STRB, the returned value is less than 0
CompareOrdinal () method, by calculating the value of the corresponding Char object in each string to compare
Method prototypes
(1) int compareordinal (string,string)//Compare two strings by calculating the value of the corresponding Char object in each string
int dou = string.compareordinal ("A", "C"); The output is:-2
Also sorted by dictionary
If STRA&GT;STRB, the value returned is greater than 0
If STRA=STRB, the returned value is equal to 0
If STRA&LT;STRB, the returned value is less than 0
The CompareTo () method, which compares this instance to a specified object or string and returns an indication of their relative values
Method prototypes
(1) int CompareTo (Object); Compare this instance to an object
MyClass my = new MyClass ();
string s = "Sometext";
Try
{
int i = S.compareto (my);
}
catch (Exception ex)
{
Console.WriteLine (ex. Message);
}
public class MyClass {}
The output is: the type of the object must be of type string
(2) int CompareTo (string); Compares this instance to a string
String str = "a";
int s = Str.compareto ("C"); Output is-1
Also sorted by dictionary
If STRA&GT;STRB, the value returned is greater than 0
If STRA=STRB, the returned value is equal to 0
If STRA&LT;STRB, the returned value is less than 0
Equals () method to determine whether two string objects have the same value
Methodological principles
(1) bool Equals (Object); Determines whether this string instance has the same value as the specified object
StringBuilder sb = new StringBuilder ("ABCD");
String str1 = "ABCD";
Console.WriteLine (str1. Equals (SB));
Output Result: False
(2) bool Equals (String); Determines whether this instance has the same value as another specified string object
String str1 = "ABCD";
Console.WriteLine (str1. Equals ("ABCD"));
The output is true
(3) bool Equals (string,string) determines whether two specified String objects have the same value
Console.Write (String. Equals ("1234", "1234"));
The output is true
(4) bool Equals (String,stringcomparison) determines whether this string has the same value as the specified string object.
The parameters specify the culture, casing, and collation used for the comparison.
String str= "Hanyinglong";
Console.WriteLine (str. Equals ("Hanyinglong", StringComparison.OrdinalIgnoreCase));
The output is true
(5) bool Equals (String,string,stringcomparison) determines whether two specified String objects have the same value.
The parameters specify the culture, casing, and collation used for the comparison.
Console.WriteLine (String. Equals ("Adssds", "Adssds", StringComparison.OrdinalIgnoreCase));
True output result
The return value is of type bool, so we can tell if the result is equal returns TRUE, otherwise false
Note: It is easier to use "= =" If you only compare two strings for equality
Console.WriteLine ("Please enter a string");
String str1 = Console.ReadLine ();
Console.WriteLine ("Please enter a second string");
String str2 = Console.ReadLine ();
Comparisons that do not consider case
BOOL IsEqual = str1. ToLower () = = str2. ToLower ();
1.4 Merging and splitting of strings
Merge Join method: Concatenates the specified delimiter string between each element of the specified string array, resulting in a single concatenated string.
Method prototypes
Details: Stitching the contents of the array Strarr into a string and adding delimiters between each of the corresponding array str
String. Join (Str,strarr);
(1) String string. Join (string,string[]);
Console.WriteLine (String. Join ("Welcome", new string[] {"Han", "Dragon", "I"}));
Console.WriteLine (String. Join ("Ying", new char[] {' Han ', ' dragon ', ' I '));
The output is: Han Guanlong greet me
(2) String string. Join (String,string[],int32,int32)
String[] val = {"Apple", "orange", "Grape", "pear"};
String Sep = ",";
String result = String.Join (Sep, Val, 1, 2);
Console.WriteLine (result);
The output is Orange,grape
Split Split method: The returned string array contains substrings in this instance
Method prototypes
(1) string[] Split (char[])//Returns a string array containing substrings from this instance
String str = "I have a Dream";
string[] Divisionstr = str. Split (new char[] {'});
foreach (string s in Divisionstr)
{
Console.Write (s);
}
The output is: Ihavedream, remove the space
(2) string[] Split (CHAR[],INT32)//The character returned contains the substring in this instance, and the parameter specifies the maximum number of substrings returned
String str = "I have a Dream";
string[] Divisionstr = str. Split (new char[] {"}, 2);
foreach (string s in Divisionstr)
{
Console.Write (s);
}
Output: Ihave a Dream, int count the meaning of the string truncated to a few paragraphs
(3) string[] Split (char[],stringsplitoptions)//The string returned contains the substring in this instance, and the parameter specifies whether
Returns an empty array element
String str = "Lionel Messi | Kaka | "Dragon";
string[] Divisionstr = str. Split (new char[] {' | ', ' '}, stringsplitoptions.removeemptyentries);
foreach (string s in Divisionstr)
{
Console.Write (s);
}
The output is: Mesicaca
(4) string[] Split (string[],stringsplitoptions)//The string returned contains the substring in this instance, and the parameter specifies whether
Returns an empty array element
String str = "Macy | kaka | Dragons";
string[] Divisionstr = str. Split (new string[] {"|"}, stringsplitoptions.removeemptyentries);
foreach (string s in Divisionstr)
{
Console.Write (s);
}
The output is: Mesicaca
(5) string[] Split (char[],int32,stringsplitoptions)//Returns a string array containing substrings in this string, parameters
Specifies the maximum number of substrings to return, and whether to return an empty array element.
String str = "Macy | kaka | Dragons";
string[] Divisionstr = str. Split (new char[] {' | '}, 2, stringsplitoptions.removeemptyentries);
foreach (string s in Divisionstr)
{
Console.Write (s);
}
The output is: Mesicaca | dragon
(6) string[] Split (string[],int32,stringsplitoptions)//Returns a string array containing substrings in this string, parameters
Specifies the maximum number of substrings to return, and whether to return an empty array element.
String str = "Macy | kaka | Dragons";
string[] Divisionstr = str. Split (new string[] {"|"}, 2, stringsplitoptions.removeemptyentries);
foreach (string s in Divisionstr)
{
Console.Write (s);
}
The output is: Mesicaca | dragon
1.5 Searching for strings
Contains method: Returns a value that indicates whether the specified string object appears in this string
Method prototypes
bool <strname>. Contains (String value); Indicates whether the string <strName> contains value, if contained, returns TRUE, otherwise false
Console.Write ("Please enter a string:");
String str = Console.ReadLine ();
if (str. Contains ("abc"))
{
Console.WriteLine ("String {0} contains {1}", str, "ABC");
}
Else
{
Console.WriteLine ("String {0} does not contain {1}", str, "ABC");
}
IndexOf method: String or one or more characters in the first occurrence of this string
Method prototypes
(1) int <strname>. IndexOf (String) specifies the index of the first occurrence of a character in this string
String str = "Make the World a better place";
int res = str. IndexOf ("good");
Console.WriteLine (RES);
Output is: 7
(2) int <strname>. IndexOf (STRING,INT32) specifies the index of the first occurrence in a string, starting at the specified character position
String str = "Make the World a better place";
int res = str. IndexOf ("The World becomes", 0);
Console.WriteLine (RES);
Output is: 1
LastIndexOf method: String or one of the last occurrences of a live multiple character in this string
Method prototypes
(1) int <strname>. LastIndexOf (String) specifies the index of the last occurrence of a character in a string
String str = "Make the World a better place";
int res = str. LastIndexOf ("good");
Console.WriteLine (RES);
Output results: 7
(2) int <strname>. LastIndexOf (STRING,INT32) specifies the index of the first occurrence in a string, starting at the specified character position
String str = "Make the World a better place";
int res = str. LastIndexOf ("Get", 4);
Console.WriteLine (RES);
Output is: 4
The Indexopany method specifies the index of the first occurrence of any character in a character array in this instance
Method prototypes
(1) int <strname>. Indexopany (char[]) specifies the index of the first occurrence of any character in the character array in this instance.
String str = "The Earth is beautiful, we love it";
int res = str. IndexOfAny (new char[] {' s ', ' I '});
Console.WriteLine (RES);
Output results: 0
(2) int <strname>. Indexopany (CHAR[],INT32) specifies the index of the first occurrence of any character in the character array in this instance.
Search starts at the specified character position
String str = "The Earth is beautiful, we love it";
int res = str. IndexOfAny (new char[] {' Ball ', ' I ', ' Hi '}, 0);
Console.WriteLine (RES);
Output results: 1
(3) int <strname>. Indexopany (CHAR[],INT32,INT32) specifies the index of the first occurrence of any character in the character array in this instance.
The search starts at the specified character position and checks the specified number of character positions.
String str = "The Earth is beautiful, we love it";
int res = str. IndexOfAny (new char[] {' Ball ', ' I ', ' Hi '}, 2, 5);
Console.WriteLine (RES);
Output results: 6
The Lastindexopany method and the LastIndexOf method are used basically the same
1.6 Seeking substrings
Method prototypes
(1) string <strname>. SubString (Int32) retrieves a string, starting with the specified character
String str = "I love China";
string res = str. Substring (2);
Console.WriteLine (RES);
Output: China
(2) string <strname>. SubString (Int32,int32) retrieves a string, starting with the specified character and having the specified length
String str = "I love China, long live the Chinese people";
string res = str. Substring (2, 5);
Console.WriteLine (RES);
Output: China, Chinese
Summary: string <strname>. SubString (int startindex,int length);
Extracts a string of length from the startindex position of the string strname, if the second argument is omitted until the last
1.7 Insert removal and substitution of strings
Inserting a string
Method prototypes
String <strname>. Insert (Intzv32 startindex,string value) inserts a specified string instance at the specified index location in this instance.
String str = "I China";
string res = str. Insert (1, "Love");
Console.WriteLine (RES);
Output: I love China
Summary: Insert value at the startindex position of the string <strName>, and the original character moves back, turning into a new string
Removing a string
Method prototypes
(1) string <strname>. Remove (Int32 startIndex) removes all characters from the specified position to the last position in this string
String str = "I love China, Japan and the Nation";
string res = str. Remove (4);
Console.WriteLine (RES);
Output: I love China
(2) string <strname>. Remove (Int32 startindex,int32 Length) Deletes the specified number of characters starting at the specified position
String str = "I love China Japan & Yamato Nation";
string res = str. Remove (4, 2);
Console.WriteLine (RES);

Output: I love China & Yamato Nation
Summary: Remove startindex starting from string <strName>, length string, the remaining characters are sorted in the original order
A new string, and if you omit the second argument, all the strings after the startindex are removed
Substitution of strings
Method prototypes
(1) string <strname>. Replace (char Oldchar,char Newchar) replaces Oldchar in string <strName> with Newchar
String str = "I love China & America";
string res = str. Replace (' & ', ' and ');
Console.WriteLine (RES);
Output: I love China and the United States
(2) string <strname>. Replace (string oldvalue,string new value) replaces OldValue in string <strName> with NewValue
String str = "I love China & America";
string res = str. Replace ("United States", "Celestial");
Console.WriteLine (RES);
The output is: I love China & Celestial
1.8 Judging start and end
StartsWith Start
Method prototypes
bool <strname>. StartsWith (string value) determines whether the beginning of this instance matches the specified string
String str = "I love China";
BOOL IsTrue = str. StartsWith ("I ay");
Console.WriteLine (IsTrue);
The output is: False
Endswidth End
Method prototypes
bool <strname>. EndsWith (string value) determines whether the end of this instance matches the specified string
String str = "I love China";
BOOL IsTrue = str. EndsWith ("China");
Console.WriteLine (IsTrue);
Output Result: False
1.9 Assigning values to strings
Copy method
Method prototypes
String string.copy (String str); Creates a new instance of a string with the same value as the specified string
String str = "Han Guanlong";
string res = string. Copy (str);
Console.WriteLine (RES);
The output is: Han Guanlong
CopyTo method
Method prototypes
String <strname>. CopyTo (int sourceindex,char[] Destination,int destinationindex,int count)
Copies the specified number of characters from the specified position in this instance to the specified position in the character array
String dest = "Hello World";
String Source = "Goodbye China";
char[] Destarray = dest. ToCharArray ();//convert dest into a character array
Source. CopyTo (8, Destarray, 6, 5);//copy 5 characters from the 8th word of source character and start from the 6th position of Destarray
Dest = new String (destarray);//At this time dest for "Hello China"
Console.WriteLine (dest);
The output is: Hello China

Summary: The string has immutability, the modification of the string, is actually to re-get a string, re-assign the value

C # string manipulation, transfer from Han Guanlong blog

Related Article

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.