C # string processing

Source: Internet
Author: User

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 each parameter are as follows: strA, strB -- two strings to be compared; ignoreCase -- specifies whether to consider case sensitivity. When true is used, Case sensitivity is ignored; indexA, indexB -- when you need to compare the substrings of two strings, indexA and indexB are the starting position of the substrings, length -- maximum length of the string to be compared, and culture -- The string's regional information. Return Value of the Compare method: returns a positive integer if strA> strB; returns 0 if strA = strB; returns 0 if strA 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: vc/Bvbj219a3 + 7Suo7oKPGJyPgoKPHByZSBjbGFzcz0 = "brush: java;"> string strA = "hello"; string strB = "hello"; 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 meaning of each parameter is: value -- a character or substring with positioning; startIndex -- the start position of the 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)
Meaning of each parameter: anyOf-an array of characters to be determined. The method returns the first position of any character in the array; startIndex-the start position of the 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 -- specifies 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
  
   
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)
Meaning of each parameter: 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 constringbuilder () -- initializes 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: The system overhead may be very expensive. If you want to modify strings without creating new objects, use the StringBuilder class to avoid generating too many temporary objects.

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.