C # string processing,
C # String processing. NET provides the String class and the System. Text namespace to quickly implement the String processing function.
String comparison strings refer to the dictionary-based sorting rules to determine the size of the two strings. The front letter must be smaller than the back letter. In the String class, common methods for comparing strings include Compare, CompareTo, CompareOrdinal, and Equals. The Compare method Compare is a static method of the String class. It is used to Compare two String objects. There are multiple overload methods:
Int Compare(string strA, string strB)Int Compare(string strA, string strB, bool ignoreCase)Int Compare(string strA, string strB, bool ignoreCase, CultureInfo)Int Compare(string strA, int indexA, string strB, int indexB, int length)Int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
The meanings of parameters are as follows:
- StrA, strB -- two strings to be compared;
- IgnoreCase -- specifies whether case sensitivity is taken into account. If the value is true, Case sensitivity is ignored;
- IndexA, indexB -- when we need to compare the substrings of two strings, indexA and indexB are the starting positions of the substrings respectively;
- Length -- maximum length of the string to be compared;
- Culture -- The Regional Information of the string.
The Return Value of the Compare method: If strA> strB, a positive integer is returned. If strA = strB, 0 is returned. If strA <strB, a negative integer is returned.
Using System; using System. collections. generic; using System. linq; using System. text; using System. IO; namespace ConsoleApplication1 {class Program {static void Main (string [] args) {string strA = ""; string strB = ""; // string comparison Console. writeLine (string. compare (strA, strB); Console. writeLine (string. compare (strA, strA); Console. writeLine (string. compare (strB, strA ));}}}
Output:
Note: The CompareOrdinal and Compare methods are very similar, but the regional issues are not considered. The CompareOrdinal method will not be described in detail below. The CompareTo method compares the current String object with another string object. The function is similar to the Compare method, and the return value is the same. The difference between the CompareTo method and the Compare method is that the following uses CompareTo to Compare two strings:
String strA = ""; string strB = ""; Console. WriteLine (strA. CompareTo (strB ));
The Equals method returns true if the two strings are equal. Otherwise, false is returned.
String strA = ""; string strB = ""; Console. WriteLine (string. Equals (strA, strB); Console. WriteLine (strA. Equals (strB ));
Positioning characters and substrings positioning substrings are the substrings or characters contained in a string, common methods in the String class include StartsWith/EndsWith, IndexOf/LastIndexOf, and IndexOfAny/LastIndexOfAny. The StartsWith/EndsWith StartWith method can be used to determine whether a String object starts with another substring. If yes, true is returned.
Public bool StartsWith(String value);
Value indicates the substring to be determined.
The EndsWith method is used to determine whether a String object ends with another substring. The IndexOf/LastIndexOf IndexOf method is used to search for the first occurrence of a specific character or string in the previous string. This method is case sensitive and starts from the first character of the string and starts with 0. If the string does not contain this character or substring,-1 is returned. IndexOf mainly has the following overload forms: positioning characters
Int IndexOf(char value)Int IndexOf(char value, int startIndex)Int IndexOf(char value, int startIndex, int count)
Locate substrings
int IndexOf(string value)int IndexOf(string value, int startIndex)int IndexOf(string value, int startIndex, int count)
The meanings of parameters are as follows:
- Value -- a character or substring with positioning;
- StartIndex-start position of the Start search in the total string;
- Count -- the number of characters that are searched from the start position in the total string.
string strA = "Hello";Console.WriteLine(strA.IndexOf('l'));
Similar to IndexOf, LastIndexOf is used to search for the last occurrence of a specific character or substring in a string.
The IndexOfAny/LastIndexOfAny IndexOfAny method is similar to IndexOf. The difference is that it can search a string for the first occurrence of any character in a character array. Similarly, this method is case sensitive and starts from the first character of a string and starts with 0. If the string does not contain this character or substring,-1 is returned. IndexOfAny has the following overload forms:
int IndexOfAny(char[] anyOf)int IndexOfAny(char[] anyOf, int startIndex)int IndexOfAny(char[] anyOf, int startIndex, int count)
Meanings of parameters:
- AnyOf -- an array of characters with to be determined characters. The method returns the first position of any character in the array;
- StartIndex-start position of the Start search in the total string;
- Count -- the number of characters that are searched from the start position in the total string.
string strA = "Hello";char[] anyOf = { 'e', 'o' };Console.WriteLine(Convert.ToString(strA.IndexOfAny(anyOf)));Console.WriteLine(Convert.ToString(strA.LastIndexOfAny(anyOf)));
Similar to IndexOfAny, LastIndexOfAny is used to search a string for the last occurrence of any character in a character array.
The Format string Format method is used to create formatted strings and connect multiple string objects. The most common form of overload is
public static string Format(string Format, params object[] arge);
- Format -- used to specify the format of the returned string;
- Args-a series of variable parameters.
string newStr = string.Format("{0},{1}!!!", strA, strB);
In specific applications, the Format method is also very convenient. For example, format the current time in the form of "YYYY-MM-DD:
DateTime DTA = DateTime.Now();string strB = string.Format("{0:d}", DTA);
Note: {0: d} refers to formatting the time into a short date representation. To intercept a String, you must use the Substring method of the String class. This method is used to retrieve a Substring from character transmission. The Substring is reloaded as follows, the substring starts from the specified character position.
public string Substring(int startIndex)
StartIndex-start character position of the string neutron string. Return Value: A String object, which is the substring starting with startIndex in the String. If startIndex is equal to the length of the String, Empty is returned. Returns a substring from a string. The substring starts from a specified character position and has a specified length.
public string Substring(int startIndex, int length)
StartIndex-start character position of the string neutron string. Length -- the number of characters in the substring. Return Value: A String object that is equal to the length of the Child String starting with startIndex. If startIndex is equal to the length of the String and the length is 0, Empty is returned.
You can use the Split method to Split a string into a series of small strings based on a separator. The Split method has multiple overload forms, the most common:
public string[] split(params char[] separator);
Separator-an array that contains delimiters.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; char[] separator={'^'}; string[] splitstrings=new string[100]; splitstrings=strA.Split(separator); int i= 0; while(i<splitstrings.Length) { Console.WriteLine("item{0}:{1}",i,splitstrings[i]); i++; } Console.ReadLine(); } }}
Output:
You can use the Insert method to Insert or populate a String to Insert any character anywhere in the String. The PadLeft/PadRight method can be used to fill in characters on both sides of a string. The Insert method is used to Insert another string at the specified position of a string to construct a new string. The most common form of overload:
public string Insert(int startIndex, string value);
StartIndex -- used to specify the location where the index is to be inserted. The index starts from 0. Value -- specifies the string to be inserted. Return value -- specify a new String equivalent of the String, but insert the value at the position startIndex.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; string strB = "Good morning!"; string newStr = strA.Insert(1, strB); Console.WriteLine(newStr); Console.ReadLine(); } }}
Output:
PadLeft/PadRight PadLeft is used to fill in characters on the left side of a string so that it reaches a certain length. There are the following overload forms:
public string PadLeft(int totalWidth)public string PadLeft(int totalWidth, char paddingChar)
TotalWidth -- specify the character length after filling. PaddingChar -- specifies the character to be filled. If default, it is filled with space characters.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; string newStr; newStr = strA.PadLeft(16, '*'); Console.WriteLine(newStr); Console.ReadLine(); } }}
Output:
The PadRight function is similar. The Delete and cut String class uses Remove to delete any length sub-String at any position of the String. You can also use Trim, TrimEnd, and TrimStart to cut out some specific strings in the String. The Remove method removes a specified number of characters from the specified position of a string. The most common syntax format:
Public String Remove(int startIndex, int count);
StartIndex -- used to specify the location where the deletion starts. The index starts from 0. Count -- specify the number of characters to delete.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; string newStr; newStr = strA.PadLeft(16, '*'); Console.WriteLine(newStr); Console.WriteLine(newStr.Remove(2, 3)); Console.ReadLine(); } }}
Output:
The Trim method is used to remove all matching items of white spaces from the start position and end of a string.
public string Trim()
Return Value-a new String, which is equivalent to a String formed after the first blank character of the specified String is removed. Removes all matching items for a group of characters specified in the array from the start position and end of the string.
public string Trim(params char[] trimChars)
TrimChars -- the array contains the characters to be removed. If the default value is used, the space symbol is deleted ). Return Value -- removes the remaining String after all matching items of the characters in trimChars from the start and end of the specified String.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; string newStr; newStr = strA.PadLeft(16, '*'); Console.WriteLine(newStr); char[] strB={'*','d'}; Console.WriteLine(newStr.Trim(strB)); Console.ReadLine(); } }}
Output:
The TrimStart method is used to remove all matching items of a specified group of characters from the starting position of a string.
public string TrimStart(params char[] trimChars)
TrimChars -- the array contains the characters to be removed. If the default value is used, the space symbol is deleted ).
Return Value -- remove the remaining String after all matching items of the characters in trimChars from the starting position of the specified String.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; char[] strB = { 'H', 'o' }; string strC = strA.TrimStart(strB); Console.WriteLine(strC); Console.Read(); } }}
Output:
PS: note that characters are case sensitive. If "h" is changed, the output is Hello ^ World. The TrimEnd method is similar to TrimStart. The Copy String class contains two methods for copying strings: Copy and CopyTo. To assign a value to another character array, use the static Copy method of String.
public static string Copy(string str);
Str -- the source string to be copied. The method returns the target string. Return Value -- A New String with the same value as str. The CopyTo method provides more functions. You can copy part of the source string to a character array. In addition, it is not a static method.
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
Meanings of parameters:
- SourceIndex -- start position of the character to be copied.
- Destination-an array of target characters.
- DestinationIndex -- specify the initial storage location of the target array.
- Count -- specifies the number of characters to be copied.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello^^world"; char[] strB = new char[100]; strA.CopyTo(3, strB, 0, 3); Console.WriteLine(strB); Console.Read(); } }}
Output:
If you want to replace a string with certain characters or substrings, you can use the Repalce method. The Replace method has the following syntax:
public string Replace(char oldChar,char newChar)public string Replace(string oldValue,string newValue)
- OldChar -- the character to be replaced.
- OldChar -- the substring to be replaced.
- NewChar -- new character after replacement.
- NewValue -- New substring after replacement.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string strA = "Hello"; string strB=strA.Replace("ll","r"); Console.WriteLine(strB); Console.Read(); } }}
Output:
The definition of StringBuilder and the use of StringBuilder class are located in the System. Text namespace, which represents a variable string. StringBuilder Definition
StringBuilder myStringBuilder=new StringBuilder();
StringBuilder constructor:
- StringBuilder () -- initialize a new instance of the StringBuilder class.
- StringBuilder (Int32) -- use the specified capacity to initialize a new instance of the StringBuilder class.
- StringBuilder (String) -- use the specified String to initialize a new instance of the StringBuilder class.
- StringBuilder (Int32, Int32) -- initializes a new instance of the StringBuilder class, which starts with the specified capacity and can be increased to the specified maximum capacity.
- StringBuilder (String, Int32) -- uses the specified String and capacity to initialize a new instance of the StringBuilder class.
- StringBuilder (String, Int32, Int32, Int32) -- use the specified substring and capacity to initialize a new instance of the StringBuilder class.
Common Properties of StringBuilder class:
- Capacity -- gets or sets the maximum number of characters that can be included in the memory allocated by the current instance.
- Chars -- gets or sets the characters at the specified character position in this instance.
- Length -- get or set the Length of the instance.
- MaxCapacity -- get the maximum capacity of this instance.
Common StringBuilder methods:
- Append -- Append the string representation of the specified object to the end of this instance.
- AppendFormat -- append zero or more formatted strings to this instance. Each format specification is replaced by the string representation of the corresponding object.
- AppendLine -- append the default line terminator (or a copy of the specified string and the default line terminator) to the end of this instance.
- CopyTo -- copy the characters in the specified segment of the instance to the specified segment of the target Char array.
- EnsureCapacity -- the capacity of this instance of StringBuilder must be at least the specified value.
- Insert -- Insert the string representation of the specified object to the specified character position in this instance.
- Remove -- Remove characters in the specified range from the instance.
- Replace -- Replace all specified characters or strings in this instance with other specified characters or strings.
- ToString -- convert the value of StringBuilder to String.
The StringBuilder class indicates an object whose values are variable character sequences. The reason for the variable value is that the created instance can modify the value after appending, deleting, replacing, or inserting a character. Almost all instance methods for modifying this type return references to the same instance. The capacity of StringBuilder is the maximum number of characters that can be stored by the instance at any given time, and the length in the string representation that is greater than or equal to the Instance value. Capacity can be increased or decreased by using the Capacity attribute or EnsureCapacity method, but cannot be smaller than the value of the Length attribute.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { StringBuilder Builder = new StringBuilder("Hello", 100); Builder.Append(" World"); Console.WriteLine(Builder); Builder.AppendFormat("{0} End", "@"); Console.WriteLine(Builder); Builder.AppendLine("This is one line."); Console.WriteLine(Builder); Builder.Insert(0, "Begin"); Console.WriteLine(Builder); Builder.Remove(19, Builder.Length - 19); Console.WriteLine(Builder); Builder.Replace("Begin", "Begin:"); Console.WriteLine(Builder); Console.ReadLine(); } }}
Output:
Differences between variable String StringBuilder and String each time you use the String method, you must create a new String object in the memory and allocate new space for the object. The system overhead may be very expensive if you need to modify the string repeatedly. If you want to modify strings without creating new objects, use the StringBuilder class to avoid generating too many temporary objects.
In C language-> what?
-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */
For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!
In C language-> what?
-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */
For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!