Use of strings

xiaoxiao2021-03-06  84

Use of strings

First, marker

TOKENIZING is the process of extracting specific content from text. The following code extracts words from the sentence and outputs them to the console. Class mytokenizing {static void main (string [] args) {string mystring = "i like this food, is you?"; char [] separators = {'', ',', '?', ':', '! '}; Int startPOS = 0; int endpos = 0; do {endpos = mystring.indexofany (separators, startpos); if (endpos == - 1) endpos = mystring.length; if (endpos! = Startpos) console.writeline (MyString.substring (startpos, (endpos-startpos))); startpos = (endpos 1);} while (startpos

Second, reverse string order class myreverse {static void main (string [] args) {string mystring = "Hello"; char [] mychars = mystring.tochararray (); array.reverse (MyChars); console.writeline Console.Writeline (MyChars);}} Any class inherited from Array can use the Reverse () method to reorder the elements in the array.

Third, the insertion of the string, delete, and replacing the sample file Test.txt is the source of the string. The following code reads text in Unicode format. Make sure the file is saved as a format when reading. Such as Notepad allows you to save code Unicode: aaaaaaaa, bbbbbbbb, ccccccdddddddd, eeeeeeee, ffffffgggggggg, hhhhhhhh, iiiiiijjjjjjjj, kkkkkkkk, llllll following code loads the data processing and data testing tool. The test results are sent to the console. class myprocessfile {static void Main (string [] args) {const string myName = "test.txt"; Stream readLine; TextWirter writeLine; StringBuilder sb; readLine = File.OpenRead (myName); WriteLine = Console.Out; StreamReader readLineSReader = new StreamReader (readLine, Encoding.Unicode); readLineSReader.BaseStream.Seek (0, SeekOrigin.Begin); while (readLineSReader.Peek ()> - 1) {sb = new StringBuilder (readLineSReader.ReadLine ()); // insert String operation statement such as: sb.append (", 123"); console.writeline (sb.tostring ());}}} Add a column at the end: // Displays Aaaaaaa, Bbbbbbbb, CCCCCC, XXXXX / / .. .... Sb.Append (", XXXXX");

The first column can be deleted using the following code: // displays bbbbbbb, cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc // ... Sb.Remove (0, sb.toString (). Indexof (',') 1);

Replace separator: //aaaaaaa bbbbbbbbbb ccccccsb.replace (',', ' ');

Add a line number (LINENUMBER has declared a premise): sb.insert (0, LINENUMBER.TOSTRING ("000")); LINENUMBER ;

// displays // 000 aaaaaaaa, bbbbbbbb, cccccc // 001 dddddddd, eeeeeeee, ffffff // 002 gggggggg, hhhhhhhh, iiiiii // 003 jjjjjjjj, kkkkkkkk, llllll

String operation

1. Extract the substring StringBuilder class from the string does not support substrings, so you must use the String class to extract. String mystring = "my name is ynn."; // displays "name is ynn." console.writeline (mystring.substring (3)); // displays "Ynn" console.writeline (11,3) );

2. Comparison string String class has four methods: Compare (), Compareto (), Compareordinal (), Equals (). The Compare () method is a static version of the Compareto () method. As long as the "=" operator, the equals () method is called, and the equals () method is equivalent to "=". CompareRinal () method compares the local language and files for both strings. Example: int result; Bool Bresult; S1 = "aaaa"; s2 = "bbb"; // COMPARE () Method // RESULT value is "0" means, less than zero means S1 S2RESULT = String.Compare (S1, S2); Result = S1.Compareto (S2); Result = String.comPareRinal (S1, S2); BRESULT = S1.Equals (S2); BRESULT = String.Equals (S1, S2); An exception is that both strings are built-in, equal, static methods are much faster. 3, string formatting

3.1 Format Digital Format Character Description and Association Attributes

C, C currency format. D, D decimal format. e, e scientific count (index) format. f, f fixed point format. g, g is regular format. n, n digital format. R, R round-trip format, ensures that the same value is the same as the original number when converting the digital conversion back to the number. X, x hexadecimal format.

Double Val = Math.pi; console.writeLine (Val.Tostring ()); // Displays 3.14159265358979console.writeline (Val.Tostring ("e")); // Displays 3.141593e 000console.writeline (Val.Tostring "F3"); // displays 3.142int val = 65535; console.writeline (Val.Tostring ("x"))); // Displays fffconsole.writeline (Val.Tostring ("x")); // Displays fffsingle Val = 0.123f; console.writeline (Val.Tostring ("P"))); // DisplayS 12.30% console.writeline (Val.Tostring ("P1")); // DisplayS 12.3% default formatting in numbers and hundred Add a space between the semicolon. The custom method is as follows: where the NumberFormatinfo class is a member of the System.globalization namespace, so the namespace must be imported into the program. Single Val = 0.123f; Object myobj = Numberformatinfo.currentInfo.clone () as NumberFormatInfo; NumberFormatInfo myformat = myobj as NumberFormatInfo; myformat.PercentPositivePattern = 1; Console.WriteLine (val.ToString ( "p", myformat)); // displays 12.30%; Console.WriteLine (val.ToString ( "p1 ", myformat); // displays 12.3%; formatted has great flexibility. The following example demonstrates a meaningful currency structure: Double Val = 1234567.89; int [] groupsize = {2, 1, 3}; Object myobj = Numberformatinfo.currentInfo.clone (); Numberformatinfo My currency = myobj as NumberFormatInfo; mycurrency.CurrencySymbol = "#"; // symbol mycurrency.CurrencyDecimalSeparator = ":"; // decimal mycurrency.CurrencyGroupSeparator = "_"; // separator mycurrency.CurrencyGroupSizes = groupsize; // output # 1_234_5_67: 89console.writeline (Val.Tostring ("C", Mycurrency);

3.2 Formatting Date Output Depending on the cultural settings of the user's computer. Using system; using system.global; public class mainclass {public static void main (string [] args) {datetime dt = DateTime.now; string [] format = {"d", "d", "f", "f" "" G "," G "," M "," R "," S "," T "," T "," U "," U "," Y "," DDDD, MMMM DD YYYY ", "DDD, MMM D /" '/ "YY", "DDDD, MMMM DD", "M / YY", "DD-MM-YY",}; String Date; For (INT I = 0; I

StringBuilder class learning notes String class's non-variableity makes it more like a value type rather than a reference type. Its side effects are created a new String object every time you perform character operations. The StringBuilder class solves the problem of creating a large number of objects during repeated modification of the string. Some properties and methods of the StringBuilder class are not read-only. Stringbuilder SB = New StringBuilder ("i live the language"); console.writeline (sb.Length = 6; // Displays "i live" console.writeline (sb.tostring ()); CAPACITY Property Description: The number of characters currently allocated for instances. The default capacity is 16. If a string is supplied as a parameter to the constructor, the capacity is the value of the most close to 2. MaxCapacity property description: The maximum number of characters that can be assigned this instance. Append () method description: A string representation of the given value. Stringbuilder SB = new stringbuilder (); console.writeline (sb.capacity "/ t" sb.Length); sb.append ('a', 17) Console.writeline (sb.capacity "/ t" sb.Length ); 16 0 <== Output 32 17 ENSURECAPACITY method Description: If the current capacity is less than the specified capacity, the memory allocation increases the memory space to achieve the specified capacity. Replace (Char Oldchar, Char Newchar) Method: Replace OldChar with Newchar. Replace (String OldString, String News) Method Description: Replace OldString with NewString. Replace (Char Oldchar, CHAR NEWCHAR, INT StartPOS, INT Count) Method: Replace Oldchar with Newchar between StartPos to Count-1. Replace (String OldString, String NewString, Int StartPOS, INT Count) Method Description: Replace OldString with NewString from StartPos to Count-1. TOSTRING () method Stringbuilder SB = New StringBuilder ("I live this game"); string S1 = sb.toString (); // displays "i live this game" string s2 = sb.toString (3, 4); // Displays "Live" here, the second toString () method calls the String class Substring () method public string toString (int StartIndex, Int length) {return m_stringvalue.substring (startIndex, length);} String class learning note one, Common public members of the String class

Static method function of Compare (String S1, STRING S2): Case size comparison. Compare (String S1, String S2, Bool Ignorecase) Static method function: IgnoreCase is True, which is not case sensitive comparison. CompareTo (String S) instance method function: Perform a case-sensitive and cultural information for a given string and an instance string. Copy (String S) Static Method Function: Returns a new string with a given string. COPYTO (int surceIndex, char [] destination, int desinterx, int count) instance method: The specified location in this instance is copied to the specified location in the Unicode characters array. Parameters: SourceIndex: Character position in this instance. Destination: A number of Unicode characters. DestinDex: Array Elements in Destination. Count: The number of characters to Destination in this instance. Routines: use system; public class copytotest {spread static void main () {string strsource = "change"; char [] destination = {'t', 'h', 'e', ​​',' i ',' N ',' I ',' T ',' I ',' A ',' L ',' ',' A ',' R ',' R ',' A ',' Y '}; Console.Writeline (destination); strsource.copyto (0, destination, 4, strsource.length); console.writeline (destination); strsource = "a Different String"; strsource.copyto (2, Destination, 3, 9); console.writeline (DESTIN);}} Output: The Initial ArrayThe Changed ArrayThedIfferentArray Endswith (String S) Features: Returns True if the instance string ends with a given string. Equals (String S) function: Returns true if the instance string has the same value as a given object. Format (iformatProvider Provider, String Format, Paramarray Args) Features: A copy of Format, where the format item has been replaced with the String equivalent of the corresponding Object instance in the ARGS. Parameter Provider: An IFORMATPROVIDER, which provides regional specific format setting information. Format: Contains zero or more format items. ARGS: An Object array containing zero or more objects to formatted.

For example: string myname = "fred"; string.format ("name = {0}, Hours = {1: hh}", myname, datetime.now); fixed text is "name =" and ", Hours =", The format item is "{0}" and "{1: hh}", the value is MyName and DateTime.now. Replace (String OldString, String News "Features: Replace all of OldString with NewString in the instance string. Split (Char [] separator, int count) Parameters Separator: Separate the Unicode character array of sub-strings in this instance, and does not contain space arrays or empty references for separators. Count: The maximum number of array elements to return. For example: String delimstr = ",.:"; Char [] delimiter = delimstr.tochararray (); string word = "ONE TWO, Three: four."; String [] split = null; split = words.split (Delimiter, 4); Foreach (String S in Split) {Console.WriteLine ("- {0} -", s);} One <== Output TWothreeFour. Substring (int StartPos, INT LENGTH) function: return one from the specified location Specifies the substring of the length. TOSTRING () Features: Returns a reference to instance characters. Tostring (iformatprovider format) Features: Returns a reference to an instance string. Regular expression learning notes (1)

First, System.Text.RegularExpression Namespace 1, the Regex class can be used to create a regular expression, but also provide a number of methods. Such as: regex.replace (String Input, String Pattern, String Replacement); ------- Regexoption enumeration IGNORECase ignores case. The default case case size is RightToleft to find the input string from right to left. NONE does not set a sign. Miltiline specifies ^ and $ can match the beginning and end of the line, and the beginning and end of the string. SINGLINE specifies special characters "." Matching any character. Except for the laundry. Example: regexoptions.ignorecaseregex.ismatch (MyString, "YWSM", regexoptions.ignorecase | regexoptions.righttoleft): ------ (two main) class constructor regex (String Pattern); regex (String Pattern, Regexoption options); Example: Match YWSM: static void main (string [] args) {regex myregex = new regex ("ywsm"); system.console.writeline (MyRegex.ismatch ("The first three letters of" "Tha Alphabet are YWSM ");} Output: True If you need to set the case-sensitive case, you can use regex myregex = new regex (" ywsm ", regexoption.ignorecase; ------- ismatch () method This method can test strings See if it matches the mode of the regular expression. If you find a match, return TRUE, otherwise false. Ismatch () has a static overload method, which can use it without explicitly create a regex object. Overloads: public bool Regex.IsMatch (string input); public bool Regex.IsMatch (string input, int startat); public static bool Regex.IsMatch (string input, string pattern); public static bool Regex.IsMatch (string input , String Pattern, Regexoption Options; INPUT: Specifies a string containing the text that will retrieve. Sartat: Specifies the start character position of the search. PTTERN: Specifies the style that will match. Options: Match behavior options. Example: string inputstring = "Welcome to the ywicc, ywsmxy!"; If (Regex.IsMatch (inputstring, "ywicc", RegexOptions.IgnoreCase)) Console.WriteLine ( "Match Found"); Else Console.WriteLine ( "No Match "); ------ Replace () method instead of a matching mode with the specified string.

--- Basic methods: public static string Regex.Replace (string input, string pattern, string replacement); public static string Regex.Replace (string input, string pattern, string replacement, RegexOption options); Example: with "AAA" Replace all instance code of "BBB": string infutstring = "Welcome to the aaa!"; Inputstring = regex.replace (InputString, "BBB", "AAA"); console.writeline (InputString); ---- non-static the method may alternatively specify a maximum number of starts and the subscript: Public string replace (string input, string replacement); Public string replace (string input, string replacement, int count); Public string replace (string input, string replacement, int count, int startat); Example: use after 456 123 XXX Alternatively, replace up to two, as follows: string inputstring = "123,456,123,123,123,789,333"; Regex regexp = new Regex ( "123"); inputstring = regexp.Replace (inputstring, "Xxx", 2, 4) Console.Writeline (InputString); Output: 123, 456, XXX, XXX, 123, 789, 333 ----- split () method is subjected to matching strings at each discovery. Returns a string array. using System; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; class mysplit {static void Main (string [] args) {string inputstring = "123,456,789, ads"; string [] splitResults; splitresults = Regex.Split (inputstring, ","); StringBuilder resultsstring = new StringBuilder (32); foreach (string stringelement in splitresults) {resultsstring.Append (stringelement "/ n");} MessageBox.Show (resultsString.ToString () );}} 123 <== result 456789ads

转载请注明原文地址:https://www.9cbs.com/read-107196.html

New Post(0)