Use notes for C # strings

Source: Internet
Author: User
Tags foreach bool comments insert instance method split string format tostring
Notes | Use of string strings


--------------------------------------------------------------------------------
One, marking
Markup (tokenizing) is the process of extracting specific content from text.
The following code extracts the words from the sentences and prints them to the console.
Class Mytokenizing
{
static void Main (string[] args)
{
String mystring= "I like this food,are for you";
Char[] separators={', ', ', '? ', ': ', '! '};
int startpos=0;
int endpos=0;
Todo
{
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<mystring. Length);
}
}
I <== Output
Like
This
Food
are
You

Second, reverse the sequence of strings
Class Myreverse
{
static void Main (string [] args)
{
String mystring= "good for You";
Char[] mychars=mystring. ToCharArray ();
Array.reverse (Mychars);
Console.WriteLine (mystring);
Console.WriteLine (Mychars);
}
}
Any class that inherits from array can use the reverse () method to reorder elements in an array.

Inserting, deleting, and replacing strings
The sample file Test.txt is the source of the string. The following code reads text in Unicode format. Make sure that the file is saved in a read-time format. For example, Notepad allows code to be saved as Unicode:
Aaaaaaaa,bbbbbbbb,cccccc
Dddddddd,eeeeeeee,ffffff
Gggggggg,hhhhhhhh,iiiiii
Jjjjjjjj,kkkkkkkk,llllll
The following code loads the data and processes the test tools for the data. 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 manipulation statements such as: SB. Append (", 123");
Console.WriteLine (sb.) ToString ());
}
}
}

Add a column at the end:
Displays aaaaaaaa,bbbbbbbb,cccccc,xxxxx
//......
Sb. Append (", xxxxx");

The first column can be deleted using the following code:
Displays BBBBBBBB,CCCCCC
//......
Sb. Remove (0,SB. ToString (). IndexOf (', ') +1);

Replace separator:
Aaaaaaaa+bbbbbbbb+cccccc
Sb. Replace (', ', ' + ');

Add line number (LineNumber has already been declared as a prerequisite in the previous place):
Sb. Insert (0,linenumber.tostring ("000"));
linenumber++;

Displays
M AAAAAAAA,BBBBBBBB,CCCCCC
001 DDDDDDDD,EEEEEEEE,FFFFFF
002 GGGGGGGG,HHHHHHHH,IIIIII
003 Jjjjjjjj,kkkkkkkk,llllll

13:16 | Comments (0)

July 11, 2004 #

String Manipulation Learning Notes
String manipulation



--------------------------------------------------------------------------------
1. Extract substring from string
The StringBuilder class does not have a method that supports substrings, so it must be extracted with the string class.
String mystring= "My name is Ynn.";
Displays "name is Ynn."
Console.WriteLine (mystring. Substring (3));
Displays "Ynn"
Console.WriteLine (mystring. Substring (11,3));

2. Comparing strings
There are four methods of the String class: Compare (), CompareTo (), compareordinal (), Equals ().
The Compare () method is a static version of the CompareTo () method. As long as the "=" operator is used, the Equals () method is called, which is equivalent to the Equals () method and "=". The CompareOrdinal () method does not test local languages and files for two strings.
Example:
int result;
BOOL Bresult;
S1= "AAAA";
S2= "BBBB";
Compare () method
Result value is "0" and so on, less than 0 means S1 < S2, greater than 0 means S1 > s2
Result=string.compare (S1,S2);
Result=s1.compareto (S2);
Result=string.compareordinal (S1,S2);
Bresult=s1. Equals (S2);
Bresult=string.equals (S1,S2);
An exception to this is that two strings are built-in and equal, and the static method is much faster.

3, string format

3.1 Formatting numbers
Format character descriptions and associated properties



--------------------------------------------------------------------------------
c, C currency format.
D, d decimal format.
E, E scientific count (index) format.
F, f fixed point format.
G, g regular format.
N, n number format.
R, r round-trip format to ensure that a number converted to a string is converted back to a number with the same value as the original number.
x, x hexadecimal format.

--------------------------------------------------------------------------------
Double Val=math.pi;
Console.WriteLine (Val. ToString ()); Displays 3.14159265358979
Console.WriteLine (Val. ToString ("E"));//displays 3.141593E+000
Console.WriteLine (Val. ToString ("F3");//displays 3.142
int val=65535;
Console.WriteLine (Val. ToString ("x")); Displays FFFF
Console.WriteLine (Val. ToString ("X")); Displays FFFF
Single val=0.123f;
Console.WriteLine (Val. ToString ("P")); Displays 12.30%
Console.WriteLine (Val. ToString ("P1")); Displays 12.3%
The default formatting puts a space between the number and the percent semicolon. The customization method is as follows:
Where the NumberFormatInfo class is a member of the System.Globalization namespace, 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.3%;
Console.WriteLine (Val. ToString ("P1", MyFormat)); Displays 12.3%;
Formatting has a lot of flexibility. The following example shows a money structure that is meaningless:
Double val=1234567.89;
int [] groupsize={2,1,3};
Object Myobj=numberformatinfo.currentinfo.clone ();
NumberFormatInfo Mycurrency=myobj as NumberFormatInfo;
Mycurrency. Currencysymbol= "#"; Symbol
Mycurrency. Currencydecimalseparator= ":"; Decimal point
Mycurrency. Currencygroupseparator= "_"; Separator
Mycurrency. Currencygroupsizes=groupsize;
Output #1_234_5_67:89
Console.WriteLine (Val. ToString ("C", mycurrency));

3.2 Format Date
The output form depends on the culture settings of the user's computer.
Using System;
Using System.Globalization;
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", "D DDD, MMMM dd "," M/yy "," Dd-mm-yy ",};
String date;
for (int i = 0; i < format. Length; i++)
{
date = dt. ToString (Format[i], datetimeformatinfo.invariantinfo);
Console.WriteLine (String.Concat (Format[i], ":", date));
}
}
}
d:07/11/2004 <======= Output
D:sunday, July 2004
F:sunday, July 2004 10:52
F:sunday, July 2004 10:52:36
g:07/11/2004 10:52
g:07/11/2004 10:52:36
M:july 11
R:sun, June 10:52:36 GMT
S:2004-07-11t10:52:36
t:10:52
T:10:52:36
U:2004-07-11 10:52:36z
U:sunday, July 2004 02:52:36
y:2004 July
dddd, MMMM DD Yyyy:sunday, July 11 2004
DDD, MMM D "'" Yy:sun, June 11 ' 04
dddd, MMMM dd:sunday, July 11
m/yy:7/04
dd-mm-yy:11-07-04

3.3 Formatting enumerations
Enum Classmen
{
Ynn=1,
yly=2,
Css=3,
C++=4
}
Gets the enumeration string information as follows:
Classmen myclassmen=classmen.yly;
Console.WriteLine (Myclassmen. ToString ()); Displays yly
Console.WriteLine (Myclassmen. ToString ("D")); Displays 2
Get the text person information from the system enumeration as follows:
DayOfWeek Day=dayofweek.friday;
Displays "Day is Friday"
Console.WriteLine (String.Format ("Day are {0:g}", day));
The format string "G" displays the enumeration as a string.

11:56 | Comments (0)

July 8, 2004 #

StringBuilder Class Learning Notes
The immutable nature of the string class makes it more like a value type than a reference type. The side effect is that each time a character operation is performed, a new string object is created. The StringBuilder class solves the problem of creating a large number of objects during a repeated modification of a string.

Some properties and methods of the StringBuilder class



--------------------------------------------------------------------------------

The Length property is not read-only.
StringBuilder sb=new StringBuilder ("I Live the Language");
Console.WriteLine (sb.) ToString ());
Sb. Length = 6;
Displays "I Live"
Console.WriteLine (sb.) ToString ());

Capacity Property
Description: The number of characters currently assigned to the instance. The default capacity is 16, and if a string is supplied as a parameter to the constructor, the capacity is at the nearest power of 2.

Maxcapacity Property
Description: The maximum number of characters that can be assigned in this instance.

Append () method
Description: Appends 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);
0 <== Output
32 17

Ensurecapacity (Int capacity) method
Description: If the current capacity is less than the specified capacity, the memory allocation increases the memory space to the specified capacity.

Replace (Char Oldchar,char Newchar) method
Description: Replaces Oldchar with Newchar.

Replace (String oldstring,string newstring) method
Description: Replaces oldstring with newstring.

Replace (Char Oldchar,char newchar,int startpos,int count) method
Description: Replaces Oldchar with Newchar from Startpos to Count-1.

Replace (String oldstring,string newstring,int startpos,int count) method
Description: Replaces 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 substring () method of the String class
Public String ToString (int startindex,int length)
{
Return m_stringvalue.substring (startindex,length);
}

10:28 | Comments (0)

July 7, 2004 #

String Class Learning Notes
Common members of a String class



--------------------------------------------------------------------------------

Compare (String s1,string s2) static method
Features: case-sensitive comparisons.

Compare (String s1,string s2,bool ignoreCase) static method
Function: IgnoreCase is true, case-insensitive comparisons are not case-sensitive.

CompareTo (String s) instance method
Function: Performs a case-sensitive comparison of the given string with the instance string in cultural information.

Copy (String s) static method
Function: Returns a new string with the same value as the given string.

CopyTo (Int surceindex,char[] destination,int destindex,int count)
Instance method functionality: The specified location in this instance is copied to the specified position in the array of Unicode characters.
Parameters:
Sourceindex: The character position in this instance.
An array of Destination:unicode characters.
The array element in the destindex:destination.
Count: The number of characters in this instance to copy to destination.
Routines:
Using System;
public class Copytotest {
public static void Main () {
String strsource = "Changed";
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 (destination); }
}
Output:
The initial array
The changed array
Thedifferentarray

EndsWith (String s)
Function: Returns True if the instance string ends with the given string.

Equals (String s)
Function: Returns True if the instance string has the same value as the given object.

Format (IFormatProvider provider,string Format,paramarray args)
Feature: A copy of format in which the format item has been replaced with a String equivalent of the corresponding Object instance in args.
Parameters
Provider: A IFormatProvider that provides culture-specific formatting information.
Format: contains 0 or more format items.
Args: An object array that contains 0 or more objects to be formatted.
For example:
String myname = "Fred";
String.Format ("Name = {0}, hours = {1:hh}", MyName, DateTime.Now);
The fixed text is "Name =" and ", hours =", the format item is "{0}" and "{1:hh}", and the value is MyName and DateTime.Now.

Replace (String oldstring,string newstring)
Function: Replaces all oldstring with newstring in an instance string.


Split (char[] separator,int count)
Parameters
Separator: An array of Unicode characters that separates the substring of this instance, an empty array that contains no delimiters, or a null reference.
Count: The maximum number of array elements to return.
For example:
String delimstr = ",.:";
char [] delimiter = Delimstr.tochararray ();
String words = "one two,three:four.";
string [] split = null;
split = words. Split (delimiter, 4);
foreach (string s in Split)
{
Console.WriteLine ("-{0}-", s);
}
One <== output
Two
Three
Four.

SubString (Int startpos,int length)
Function: Returns a substring of a specified length starting at the specified location.

ToString () function: Returns a reference to an instance character.
ToString (IFormatProvider format)
Function: Returns a reference to the instance string.

13:31 | Comments (0)

July 6, 2004 #

Regular expression Learning notes (1)
First, System.Text.RegularExpression namespaces
1. The Regex class can be used to create regular expressions, and many methods are provided.
such as: Regex.Replace (string input,string pattern,string replacement);
-------Regexoption Enumeration
IgnoreCase ignores case. The default case sensitivity is case-sensitive
RightToLeft finds the input string from right to left.
None does not set a flag.
Miltiline specifies that ^ and $ can match the beginning and end of a line, as well as the beginning and end of a string.
Singleline Specify special characters "." matches any one character. Except for line breaks.
Example: Regexoptions.ignorecase
Regex.IsMatch (Mystring, "YWSM", Regexoptions.ignorecase | Regexoptions.righttoleft):
-------(two main) class constructors
Regex (string pattern);
Regex (string pattern, regexoption options);
Example: Matching YWSM:
static void Main (string[] args)
{Regex myregex=new regex ("YWSM");
System.Console.WriteLine (Myregex. IsMatch ("The three Letters of" + "the Alphabet are Ywsm")); }
Output: True if you want to set case sensitivity available
Regex myregex=new Regex ("YWSM", regexoption.ignorecase);
-------IsMatch () method
The method can test the string to see if it matches the pattern of the regular expression. Returns true if a match is found, otherwise false. IsMatch () has a static overloaded method that you can use without explicitly creating a Regex object.
Overloaded form:
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 to retrieve.
Sartat: Specifies the starting character position of the search.
Pttern: Specifies the style to be matched.
Options: An option for matching behavior.
Example: String inputstring= "Welcome to the ywicc,ywsmxy!";
if (Regex.IsMatch (inputstring, "YWICC", Regexoptions.ignorecase))
Console.WriteLine ("Match Found");
Else
Console.WriteLine ("No Match Found");
------Replace () method
Replaces a matching pattern with the specified string.
---Basic methods are:
public static string Regex.Replace (String input,string pattern,string replacement);
public static string Regex.Replace (String input,string pattern,string replacement,regexoption options);
For example: Replace all instance code of "BBB" with "AAA":
String inputstring= "Welcome to the aaa!";
Inputstring=regex.replace (inputstring, "BBB", "AAA");
Console.WriteLine (inputstring);
----Non-static method, you can specify the maximum number of substitutions and start 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: Replace the 123 after 456 with XXX, and replace the maximum of two times with the following code:
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
Splits a string each time a matching location is found. Returns an array of strings.
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 <== Results
456
789
Ads




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.