C # string processing

Source: Internet
Author: User

C # string processing. NET provides a string class and a System.Text namespace for high-speed character-handling functions.
String comparison string refers to a dictionary-ordered rule that infers the size of two strings. The preceding letter is smaller than the following letter. In the string class, the common methods for comparing strings are compare, CompareTo, compareordinal, and equals. The Compare method Compare method is a static method of the string class for a comprehensive comparison of two string objects. Includes several overloaded 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 (s Tring stra, int indexa, string strB, int indexb, int length, bool ignoreCase)
The meanings of each of these parameters are as follows:
    • stra,strb--two strings to compare;
    • ignorecase--Specifies whether to consider uppercase and lowercase, ignoring uppercase and lowercase when true;
    • indexa,indexb--requires a substring of two strings, Indexa and Indexb are the starting positions of substrings, respectively;
    • length--the maximum length of the string to compare;
    • culture--The culture information for the string.
The return value of the Compare method: If STRA>STRB returns a positive integer; If STRA=STRB, return 0; If STRA<STRB, returns a negative integer.
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 = "Hello";            String StrB = "How are you?";            string comparison            Console.WriteLine (String.Compare (Stra, StrB));            Console.WriteLine (String.Compare (Stra, Stra));            Console.WriteLine (String.Compare (StrB, Stra));}}}    
Output:
Description: The CompareOrdinal method is similar to the Compare method, but does not take into account regional issues, and the CompareOrdinal method is no longer specifically described below.        The CompareTo method CompareTo method makes a comparison between the current string object and a string object, similar to the Compare method, and the return value is the same. The difference between the CompareTo method and the Compare method is:
    1. The CompareTo method is not a static method and can be called through a string object;
    2. The CompareTo method has no overloaded form and can only be two full strings in uppercase and lowercase sensitive ways.
The following two strings are used with CompareTo:
string stra = "Hello"; string StrB = "How are you?"; Console.WriteLine (Stra.compareto (StrB));
The Equals method assumes that two strings are equal, Equals () returns a value of true, otherwise, returns false.
string stra = "Hello"; string StrB = "How are you?"; Console.WriteLine (String. Equals (Stra, StrB)); Console.WriteLine (Stra.equals (StrB));
locating characters and substring locating substrings refers to a string in which a substring or a character is included in the search, and common methods in the string class include Startswith/endswith, Indexof/lastindexof, and indexofany/ Lastindexofany. The Startswith/endswith Startwith method can infer whether a string object starts with a substring and, if so, returns True.
public bool StartsWith (String value);
, value represents the substring to be determined.
The EndsWith method infers whether a string object ends with a substring. The Indexof/lastindexof IndexOf method is used to search for the first occurrence of a particular character or string in the previous string, which distinguishes between uppercase and lowercase, and starts at 0 from the first character of the string. If the character or substring is not included in the string, 1 is returned. IndexOf mainly has the following overloaded forms: positional characters
int IndexOf (char value) int IndexOf (char value, int startIndex) int IndexOf (char value, int startIndex, int count)
Locating substrings
int IndexOf (string value) int IndexOf (string value, int startIndex) int IndexOf (string value, int startIndex, int count)
The meaning of each of the parameters is:
    • value--a character or substring with positioning;
    • startindex--the starting position of the search in the total string;
    • count--the number of characters to search in the total string from the start position.
String stra = "Hello"; Console.WriteLine (Stra.indexof (' l '));
Similar to IndexOf, the LastIndexOf method is used to search for the last occurrence of a specific character or substring in a string.
The Indexofany/lastindexofany IndexOfAny method functions like indexof, except that it searches a string for the first occurrence of random characters in a character array. , the method distinguishes between uppercase and lowercase, and counts from the first character of the string starting at 0.        If the character or substring is not included in the string, 1 is returned. The IndexOfAny has the following overloaded form:
int IndexOfAny (char[] anyOf) int indexofany (char[] anyOf, int startIndex) int indexofany (char[] anyOf, int startIndex, int c Ount)
The meaning of each of the parameters:
    • anyof--the character array to be positioned, the method returns the position of the first occurrence of a random character in the array;
    • startindex--the starting position of the search in the total string;
    • count--the number of characters to search in the total string from the start position.
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 random characters in a character array.
The format string method is used to create a formatted string and to concatenate multiple string objects. The most frequently used overloaded form 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);
The format method is also very convenient in a particular application. For example, the current time format is "Yyyy-mm-dd" form:
DateTime DTA = DateTime.Now (); string StrB = String. Format ("{0:d}", DTA);
Description: {0:D} indicates that the time is formatted as a short date representation. Intercepting string truncation string requires the substring method of the string class, which is used to retrieve substrings from the word Chungzhong, with the following overloaded form: Retrieving substrings from a string, starting with the specified character position
public string Substring (int startIndex)
startindex--the starting character position of a substring of a string. Return value: A string object equal to the substring starting from startindex in the string, assuming that startindex equals the length of this string, returns empty. Retrieves a substring from a string, starting at the specified character position and having the specified length
public string Substring (int startIndex, int length)
startindex--the starting character position of a substring of a string.        The number of characters in the length--substring. Return value: A string object, equal to the length of a substring starting from startindex in the string, assuming that startindex equals the length of this string, and length is 0, returns empty.
Delimited strings use the split method to cut a string, according to a delimiter, into a series of small strings. The split method has several overloaded forms, the most common:
Public string[] Split (params char[] separator);
separator--an array, including 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:
Inserting and populating strings the string class can use the Insert method to insert arbitrary characters anywhere in a string. Using the Padleft/padright method, you can fill a character with the left and right sides of a string. Insert method The Insert method is used to insert a string at the specified location of a string and to construct a new string. The most frequently used overloaded form:
public string Insert (int startIndex, string value);
The startindex--is used to specify where to insert the index starting at 0.        value--Specifies the string to insert. Return value--a new string equivalent of the specified string, but insert value at 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 a character on the left side of a string so that it reaches a certain length. Has the following overloaded form:
public string PadLeft (int totalWidth) public string PadLeft (int totalWidth, char Paddingchar)
totalwidth--Specifies the length of the character after padding. paddingchar--specifies the character to be populated, assuming that the space symbol is populated by default.
Namespace consoleapplication1{    class program    {        static void Main (string[] args)        {            string stra = " Hello^^world ";            string newstr;             Newstr = Stra.padleft (+, ' * ');            Console.WriteLine (NEWSTR);            Console.ReadLine ();}}}    
Output:
PadRight function is similar, no longer repeat. Delete and cut strings The string class uses remove to remove arbitrary-length substrings anywhere in the string, and to use trim, trimend, and TrimStart to cut out some specific strings in the string. The Remove method removes the specified number of characters from the specified position of a string. The most frequently used syntax format:
Public String Remove (int startIndex, int count);
The startindex--is used to specify where to start the deletion, starting at 0. count--Specifies the number of characters to delete.
Namespace consoleapplication1{    class program    {        static void Main (string[] args)        {            string stra = " Hello^^world ";            string newstr;             Newstr = Stra.padleft (+, ' * ');            Console.WriteLine (NEWSTR);            Console.WriteLine (Newstr.remove (2, 3));            Console.ReadLine ();}}}    
Output:
The Trim method has the following overloaded form: Remove all occurrences of the white space character from the beginning and end of the string.
public string Trim ()
Return value-a new string equivalent to the string that is formed after the first white space character of the specified string is removed. Removes all occurrences of a set of characters specified in an array from the beginning and end of a string
public string Trim (params char[] trimChars)
The trimchars--array includes the specified characters to be removed, assuming the default is to remove the space symbol. return value-The string remaining after removing all occurrences of a character in trimchars from the beginning and end of the specified string.
Namespace consoleapplication1{    class program    {        static void Main (string[] args)        {            string stra = " Hello^^world ";            string newstr;             Newstr = Stra.padleft (+, ' * ');            Console.WriteLine (NEWSTR);            char[] strb={' * ', ' d '};            Console.WriteLine (Newstr.trim (StrB));            Console.ReadLine ();}}}    
Output:
The TrimStart method TrimStart method is used to remove all occurrences of a set of characters specified in the array from the beginning of the string.
public string TrimStart (params char[] trimChars)
The trimchars--array includes the specified characters to be removed, assuming the default is to remove the space symbol.
return value-The string remaining after all occurrences of a character in trimchars are removed from the beginning 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 differentiate between uppercase and lowercase. If the above changes to "H", then the output of Hello^^world is still. The TrimEnd method is analogous to TrimStart. The copy string class includes two methods for copying a string, copy and CopyTo. Copy method to assign a string to a character array, you can use the static method copy of string to implement it.
public static string Copy (String str);
The str--is the source string that needs to be copied, and the method returns the target string. Return value-A new string with the same value as Str. The CopyTo method of the CopyTo method is richer in its ability to copy part of the source string into a single character array. In addition, it is not a static method.
public void CopyTo (int sourceIndex, char[] destination, int destinationindex, int count)
The meaning of each of the parameters:
    • sourceindex--the starting position of the character that needs to be copied.
    • destination--the target character array.
    • destinationindex--Specifies the start location of the destination array.
    • count--Specifies the number of characters to copy.
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:
The replacement string assumes that you want to replace some specific character or a substring of a string, and that you can use the Repalce method. The syntax form of the Replace method mainly includes:
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--the new character after the replacement.
    • newvalue--the 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 StringBuilder definition and use of the StringBuilder class is located under the System.Text namespace, which represents a mutable string. Definition of StringBuilder
StringBuilder mystringbuilder=new StringBuilder ();
StringBuilder constructor:
    • StringBuilder ()-Initializes a new instance of the StringBuilder class.
    • StringBuilder (Int32)-Initializes a new instance of the StringBuilder class with the specified capacity.
    • StringBuilder (String)-Initializes a new instance of the StringBuilder class with the specified string.
    • StringBuilder (Int32,int32)-Initializes a new instance of the StringBuilder class that starts at the specified capacity and can grow to the specified maximum capacity.
    • StringBuilder (String,int32)-Initializes a new instance of the StringBuilder class with the specified string and capacity.
    • StringBuilder (String,int32,int32,int32)-Initializes a new instance of the StringBuilder class with the specified substring and capacity.
StringBuilder uses the StringBuilder class to frequently use attribute descriptions:
    • 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 character at the specified character position in this instance.
    • length--Gets or sets the length of this instance.
    • maxcapacity--gets the maximum capacity for this instance.
StringBuilder class frequently used method description:
    • append--appends the string representation of the specified object to the end of this instance.
    • appendformat--appends a formatted string that includes 0 or many other format specifications to this instance. Each format specification is replaced by a string representation of the corresponding object.
    • appendline--appends the default line terminator (or a copy of the specified string and the default line terminator) to the end of this instance.
    • copyto--copies the characters in the specified segment of this instance to the specified segment of the destination char array.
    • ensurecapacity--will ensure that the capacity of this instance of StringBuilder is at least the specified value.
    • insert--inserts the string representation of the specified object into the specified character position in this instance.
    • remove--removes the specified range of characters from this instance.
    • replace--replaces all of the specified characters or strings in this instance with other specified characters or strings.
    • tostring--converts the value of StringBuilder to string.
The StringBuilder class represents an object with a variable character sequence whose value is variable because the instance created with append, delete, replace, or insert characters can alter it.        Almost all changes to the instance method of this class return a reference to the same instance. The capacity of the StringBuilder is the maximum number of characters that an instance can store at any given time, and is greater than or equal to the length of the string representation of the instance value. The capacity can be added or lowered through the capacity property or the Ensurecapacity method, but not less than the value of the length property.
Namespace consoleapplication1{    class program    {        static void Main (string[] args)        {            StringBuilder Builder = new StringBuilder ("Hello", +);            Builder.append ("World");            Console.WriteLine (Builder);            Builder.appendformat ("{0} End", "@");            Console.WriteLine (Builder);            Builder.appendline ("This was one line.");            Console.WriteLine (Builder);            Builder.insert (0, "Begin");            Console.WriteLine (Builder);            Builder.remove (builder.length-19);            Console.WriteLine (Builder);            Builder.replace ("Begin", "Begin:");            Console.WriteLine (Builder);            Console.ReadLine ();}}}    
Output:
Variable String class StringBuilder and string differences each time you use the method of the string class, you create a new string object in memory, and you need to allocate a new space for the object. Overhead can be expensive in situations where the strings need to be run over and over again. Suppose you want to change a string without creating a new object, use the StringBuilder class to avoid generating too many temporary objects.

C # string processing

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.