Monday, 26 November 2012
c# for dummies: c sharp programming
c# for dummies: c sharp programming: String equality comparison Despite ordinal’s limitations, string’s == operator always performs ordinal case- sensitive comparison. The...
c sharp programming
String equality comparison
Despite ordinal’s limitations, string’s == operator always performs ordinal case-
sensitive comparison. The same goes for the instance version of string.Equals when
called without arguments; this defines the “default” equality comparison behavior
for the string type.
The ordinal algorithm was chosen for string’s == and Equals
functions because it’s both highly efficient and deterministic.
String equality comparison is considered fundamental and is
performed far more frequently than order comparison.
A “strict” notion of equality is also consistent with the general
use of the == operator.
The following methods allow culture-aware or case-insensitive comparisons:
public bool Equals(string value, StringComparison comparisonType);
public static bool Equals (string a, string b,
StringComparison comparisonType);
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
public enum StringComparison
{
CurrentCulture, // Case-sensitive
CurrentCultureIgnoreCase,
InvariantCulture, // Case-sensitive
InvariantCultureIgnoreCase,
Ordinal, // Case-sensitive
OrdinalIgnoreCase
}
For example:
Console.WriteLine (string.Equals ("foo", "FOO",
StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine ("?" == "u"); // False
Console.WriteLine (string.Equals ("?", "u",
StringComparison.CurrentCulture)); // ?
(The result of the final comparison is determined by the computer’s current language
settings.)
Despite ordinal’s limitations, string’s == operator always performs ordinal case-
sensitive comparison. The same goes for the instance version of string.Equals when
called without arguments; this defines the “default” equality comparison behavior
for the string type.
The ordinal algorithm was chosen for string’s == and Equals
functions because it’s both highly efficient and deterministic.
String equality comparison is considered fundamental and is
performed far more frequently than order comparison.
A “strict” notion of equality is also consistent with the general
use of the == operator.
The following methods allow culture-aware or case-insensitive comparisons:
public bool Equals(string value, StringComparison comparisonType);
public static bool Equals (string a, string b,
StringComparison comparisonType);
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
public enum StringComparison
{
CurrentCulture, // Case-sensitive
CurrentCultureIgnoreCase,
InvariantCulture, // Case-sensitive
InvariantCultureIgnoreCase,
Ordinal, // Case-sensitive
OrdinalIgnoreCase
}
For example:
Console.WriteLine (string.Equals ("foo", "FOO",
StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine ("?" == "u"); // False
Console.WriteLine (string.Equals ("?", "u",
StringComparison.CurrentCulture)); // ?
(The result of the final comparison is determined by the computer’s current language
settings.)
c# for dummies: StringBuilder in c#
c# for dummies: StringBuilder in c#: StringBuilder The StringBuilder class (System.Text namespace) represents a mutable (editable) string. With a StringBuilder, you can Append, ...
StringBuilder in c#
StringBuilder
The StringBuilder class (System.Text namespace) represents a mutable (editable)
string. With a StringBuilder, you can Append, Insert, Remove, and Replace substrings
without replacing the whole StringBuilder.
StringBuilder’s constructor optionally accepts an initial string value, as well as a
starting size for its internal capacity (default is 16 characters). If you go above this,
StringBuilder automatically resizes its internal structures to accommodate (at a
slight performance cost) up to its maximum capacity (default is int.MaxValue).
A popular use of StringBuilder is to build up a long string by repeatedly calling
Append. This approach is much more efficient than repeatedly concatenating ordi-
nary string types:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) sb.Append (i + ",");
To get the final result, call ToString():
Console.WriteLine (sb.ToString());
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
In our example, the expression i + "," means that we’re still
repeatedly concatenating strings. However, this incurs only a
small performance cost in that the strings in question are small
and don’t grow with each loop iteration. For maximum per-
formance, however, we could change the loop body to this:
{ sb.Append (i.ToString()); sb.Append (","); }
AppendLine performs an Append that adds a new line sequence ("\r\n" in Windows).
AppendFormat accepts a composite format string, just like String.Format.
As well as the Insert, Remove, and Replace methods (Replace functions such as
string’s Replace), StringBuilder defines a Length property and a writable indexer for
getting/setting individual characters.
To clear the contents of a StringBuilder, either instantiate a new one or set its
Length to zero.
Setting a StringBuilder’s Length to zero doesn’t shrink its in-
ternal capacity. So, if the StringBuilder previously contained 1
million characters, it will continue to occupy around 2 MB of
memory after zeroing its Length. If you want to release the mem-
ory, you must create a new StringBuilder and allow the old one
to drop out of scope (and be garbage-collected).
The StringBuilder class (System.Text namespace) represents a mutable (editable)
string. With a StringBuilder, you can Append, Insert, Remove, and Replace substrings
without replacing the whole StringBuilder.
StringBuilder’s constructor optionally accepts an initial string value, as well as a
starting size for its internal capacity (default is 16 characters). If you go above this,
StringBuilder automatically resizes its internal structures to accommodate (at a
slight performance cost) up to its maximum capacity (default is int.MaxValue).
A popular use of StringBuilder is to build up a long string by repeatedly calling
Append. This approach is much more efficient than repeatedly concatenating ordi-
nary string types:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) sb.Append (i + ",");
To get the final result, call ToString():
Console.WriteLine (sb.ToString());
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
In our example, the expression i + "," means that we’re still
repeatedly concatenating strings. However, this incurs only a
small performance cost in that the strings in question are small
and don’t grow with each loop iteration. For maximum per-
formance, however, we could change the loop body to this:
{ sb.Append (i.ToString()); sb.Append (","); }
AppendLine performs an Append that adds a new line sequence ("\r\n" in Windows).
AppendFormat accepts a composite format string, just like String.Format.
As well as the Insert, Remove, and Replace methods (Replace functions such as
string’s Replace), StringBuilder defines a Length property and a writable indexer for
getting/setting individual characters.
To clear the contents of a StringBuilder, either instantiate a new one or set its
Length to zero.
Setting a StringBuilder’s Length to zero doesn’t shrink its in-
ternal capacity. So, if the StringBuilder previously contained 1
million characters, it will continue to occupy around 2 MB of
memory after zeroing its Length. If you want to release the mem-
ory, you must create a new StringBuilder and allow the old one
to drop out of scope (and be garbage-collected).
c# for dummies: c sharp programming
c# for dummies: c sharp programming: String order comparison String’s CompareTo instance method performs culture-sensitive, case-sensitive order comparison. Unlike the == operat...
c sharp programming
String order comparison
String’s CompareTo instance method performs culture-sensitive, case-sensitive order
comparison. Unlike the == operator, CompareTo does not use ordinal comparison: for
ordering, a culture-sensitive algorithm is much more useful.
Here’s the method’s definition:
public int CompareTo (string strB);
The CompareTo instance method implements the generic
IComparable interface, a standard comparison protocol used
across the .NET Framework. This means string’s CompareTo
defines the default ordering behavior strings, in such applica-
tions as sorted collections, for instance. For more information
For other kinds of comparison, you can call the static Compare and CompareOrdinal
methods:
public static int Compare (string strA, string strB,
StringComparison comparisonType);
public static int Compare (string strA, string strB, bool ignoreCase,
CultureInfo culture);
public static int Compare (string strA, string strB, bool ignoreCase);
public static int CompareOrdinal (string strA, string strB);
The last two methods are simply shortcuts for calling the first two methods.
All of the order comparison methods return a positive number, a negative number,
or zero, depending on whether the first value comes after, before, or alongside the
second value:
Console.WriteLine ("Boston".CompareTo ("Austin")); // 1
Console.WriteLine ("Boston".CompareTo ("Boston")); // 0
Console.WriteLine ("Boston".CompareTo ("Chicago")); // -1
Console.WriteLine ("?".CompareTo ("u")); // 0
Console.WriteLine ("foo".CompareTo ("FOO")); // -1
The following performs a case-insensitive comparison using the current culture:
Console.WriteLine (string.Compare ("foo", "FOO", true)); // 0
By supplying a CultureInfo object, you can plug in any alphabet:
// CultureInfo is defined in the System.Globalization namespace
CultureInfo german = CultureInfo.GetCultureInfo ("de-DE");
int i = string.Compare ("Müller", "Muller", false, german);
String’s CompareTo instance method performs culture-sensitive, case-sensitive order
comparison. Unlike the == operator, CompareTo does not use ordinal comparison: for
ordering, a culture-sensitive algorithm is much more useful.
Here’s the method’s definition:
public int CompareTo (string strB);
The CompareTo instance method implements the generic
IComparable interface, a standard comparison protocol used
across the .NET Framework. This means string’s CompareTo
defines the default ordering behavior strings, in such applica-
tions as sorted collections, for instance. For more information
For other kinds of comparison, you can call the static Compare and CompareOrdinal
methods:
public static int Compare (string strA, string strB,
StringComparison comparisonType);
public static int Compare (string strA, string strB, bool ignoreCase,
CultureInfo culture);
public static int Compare (string strA, string strB, bool ignoreCase);
public static int CompareOrdinal (string strA, string strB);
The last two methods are simply shortcuts for calling the first two methods.
All of the order comparison methods return a positive number, a negative number,
or zero, depending on whether the first value comes after, before, or alongside the
second value:
Console.WriteLine ("Boston".CompareTo ("Austin")); // 1
Console.WriteLine ("Boston".CompareTo ("Boston")); // 0
Console.WriteLine ("Boston".CompareTo ("Chicago")); // -1
Console.WriteLine ("?".CompareTo ("u")); // 0
Console.WriteLine ("foo".CompareTo ("FOO")); // -1
The following performs a case-insensitive comparison using the current culture:
Console.WriteLine (string.Compare ("foo", "FOO", true)); // 0
By supplying a CultureInfo object, you can plug in any alphabet:
// CultureInfo is defined in the System.Globalization namespace
CultureInfo german = CultureInfo.GetCultureInfo ("de-DE");
int i = string.Compare ("Müller", "Muller", false, german);
c# for dummies: c sharp programming
c# for dummies: c sharp programming: Ordinal versus culture comparison There are two basic algorithms for string comparison: ordinal and culture-sensitive. Ordinal comparisons ...
c sharp programming
Ordinal versus culture comparison
There are two basic algorithms for string comparison: ordinal and culture-sensitive.
Ordinal comparisons interpret characters simply as numbers (according to their
numeric Unicode value); culture-sensitive comparisons interpret characters with
reference to a particular alphabet. There are two special cultures: the “current cul-
ture,” which is based on settings picked up from the computer’s control panel, and
the “invariant culture,” which is the same on every computer (and closely maps
American culture).
For equality comparison, both ordinal and culture-specific algorithms are useful.
For ordering, however, culture-specific comparison is nearly always preferable: to
order strings alphabetically, you need an alphabet. Ordinal relies on the numeric
Unicode point values, which happen to put English characters in alphabetical
order—but even then not exactly as you might expect. For example, assuming case-
sensitivity, consider the strings “Atom”, “atom”, and “Zamia”. The invariant culture
puts them in the following order:
"Atom", "atom", "Zamia"
Ordinal arranges them instead as follows:
"Atom", "Zamia", "atom"
This is because the invariant culture encapsulates an alphabet, which considers up-
percase characters adjacent to their lowercase counterparts (AaBbCcDd…). The or-
dinal algorithm, however, puts all the uppercase characters first, and then all
lowercase characters (A..Z, a..z). This is essentially a throwback to the ASCII char-
acter set invented in the 1960s.
There are two basic algorithms for string comparison: ordinal and culture-sensitive.
Ordinal comparisons interpret characters simply as numbers (according to their
numeric Unicode value); culture-sensitive comparisons interpret characters with
reference to a particular alphabet. There are two special cultures: the “current cul-
ture,” which is based on settings picked up from the computer’s control panel, and
the “invariant culture,” which is the same on every computer (and closely maps
American culture).
For equality comparison, both ordinal and culture-specific algorithms are useful.
For ordering, however, culture-specific comparison is nearly always preferable: to
order strings alphabetically, you need an alphabet. Ordinal relies on the numeric
Unicode point values, which happen to put English characters in alphabetical
order—but even then not exactly as you might expect. For example, assuming case-
sensitivity, consider the strings “Atom”, “atom”, and “Zamia”. The invariant culture
puts them in the following order:
"Atom", "atom", "Zamia"
Ordinal arranges them instead as follows:
"Atom", "Zamia", "atom"
This is because the invariant culture encapsulates an alphabet, which considers up-
percase characters adjacent to their lowercase counterparts (AaBbCcDd…). The or-
dinal algorithm, however, puts all the uppercase characters first, and then all
lowercase characters (A..Z, a..z). This is essentially a throwback to the ASCII char-
acter set invented in the 1960s.
c# for dummies: Comparing Strings in c#
c# for dummies: Comparing Strings in c#: Comparing Strings In comparing two values, the .NET Framework differentiates the concepts of equal- ity comparison and order comparison. Equ...
Comparing Strings in c#
Comparing Strings
In comparing two values, the .NET Framework differentiates the concepts of equal-
ity comparison and order comparison. Equality comparison tests whether two in-
stances are semantically the same; order comparison tests which of two (if any)
instances comes first when arranging them in ascending or descending sequence.
Equality comparison is not a subset of order comparison; the
two systems have different purposes. It’s legal, for instance, to
have two unequal values in the same ordering position. We re-
sume this topic in “Equality Comparison” on page 245.
For string equality comparison, you can use the == operator or one of string’s
Equals methods. The latter are more versatile because they allow you to specify
options such as case-insensitivity.
Another difference is that == does not work reliably on strings
if the variables are cast to the object type.
For string order comparison, you can use either the CompareTo instance method or
the static Compare and CompareOrdinal methods: these return a positive or negative
number—or zero—depending on whether the first value comes before, after, or
alongside the second.
Before going into the details of each, we need to examine .NET’s underlying string
comparison algorithms.
In comparing two values, the .NET Framework differentiates the concepts of equal-
ity comparison and order comparison. Equality comparison tests whether two in-
stances are semantically the same; order comparison tests which of two (if any)
instances comes first when arranging them in ascending or descending sequence.
Equality comparison is not a subset of order comparison; the
two systems have different purposes. It’s legal, for instance, to
have two unequal values in the same ordering position. We re-
sume this topic in “Equality Comparison” on page 245.
For string equality comparison, you can use the == operator or one of string’s
Equals methods. The latter are more versatile because they allow you to specify
options such as case-insensitivity.
Another difference is that == does not work reliably on strings
if the variables are cast to the object type.
For string order comparison, you can use either the CompareTo instance method or
the static Compare and CompareOrdinal methods: these return a positive or negative
number—or zero—depending on whether the first value comes before, after, or
alongside the second.
Before going into the details of each, we need to examine .NET’s underlying string
comparison algorithms.
c# for dummies: c# for dummies
c# for dummies: c# for dummies: String.Format and composite format strings The static Format method provides a convenient way to build strings that embed variables. The ...
c# for dummies
String.Format and composite format strings
The static Format method provides a convenient way to build strings that embed
variables. The embedded variables can be of any type; the Format simply calls
ToString on them.
The master string that includes the embedded variables is called a composite format
string. When calling String.Format, you provide a composite format string followed
by each of the embedded variables. For example:
string composite = "It's {0} degrees in {1} on this {2} morning";
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);
// s == "It's 35 degrees in Perth on this Friday morning"
(And that’s Celsius!)
Each number in curly braces is called a format item. The number corresponds to the
argument position and is optionally followed by:
• A comma and a minimum width to apply
• A colon and a format string
The minimum width is useful for aligning columns. If the value is negative, th
is left-aligned; otherwise, it’s right-aligned. For example:
string composite = "Name={0,-20} Credit Limit={1,15:C}";
Console.WriteLine (string.Format (composite, "Mary", 500));
Console.WriteLine (string.Format (composite, "Elizabeth", 20000));
Here’s the result:
Name=Mary Credit Limit= $500.00
Name=Elizabeth Credit Limit= $20,000.00
The equivalent without using string.Format is this:
string s = "Name=" + "Mary".PadRight (20) +
" Credit Limit=" + 500.ToString ("C").PadLeft (15);
The static Format method provides a convenient way to build strings that embed
variables. The embedded variables can be of any type; the Format simply calls
ToString on them.
The master string that includes the embedded variables is called a composite format
string. When calling String.Format, you provide a composite format string followed
by each of the embedded variables. For example:
string composite = "It's {0} degrees in {1} on this {2} morning";
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);
// s == "It's 35 degrees in Perth on this Friday morning"
(And that’s Celsius!)
Each number in curly braces is called a format item. The number corresponds to the
argument position and is optionally followed by:
• A comma and a minimum width to apply
• A colon and a format string
The minimum width is useful for aligning columns. If the value is negative, th
is left-aligned; otherwise, it’s right-aligned. For example:
string composite = "Name={0,-20} Credit Limit={1,15:C}";
Console.WriteLine (string.Format (composite, "Mary", 500));
Console.WriteLine (string.Format (composite, "Elizabeth", 20000));
Here’s the result:
Name=Mary Credit Limit= $500.00
Name=Elizabeth Credit Limit= $20,000.00
The equivalent without using string.Format is this:
string s = "Name=" + "Mary".PadRight (20) +
" Credit Limit=" + 500.ToString ("C").PadLeft (15);
c# for dummies: c sharp classes
c# for dummies: c sharp classes: Splitting and joining strings Split takes a sentence and returns an array of words: string[] words = "The quick brown fox".Split(); foreach ...
c sharp classes
Splitting and joining strings
Split takes a sentence and returns an array of words:
string[] words = "The quick brown fox".Split();
foreach (string word in words)
Console.Write (word + "|"); // The|quick|brown|fox|
By default, Split uses whitespace characters as delimiters; it’s also overloaded to
accept a params array of char or string delimiters. Split also optionally accepts a
StringSplitOptions enum, which has an option to remove empty entries: this is
useful when words are separated by several delimiters in a row.
The static Join method does the reverse of Split. It requires a delimiter and string
array:
string[] words = "The quick brown fox".Split();
string together = string.Join (" ", words); // The quick brown fox
The static Concat method is similar to Join but accepts only a params string array and
applies no separator. Concat is exactly equivalent to the + operator (the compiler, in
fact, translates + to Concat):
string sentence = string.Concat ("The", " quick", " brown", " fox");
string sameSentence = "The" + " quick" + " brown" + " fox";
Split takes a sentence and returns an array of words:
string[] words = "The quick brown fox".Split();
foreach (string word in words)
Console.Write (word + "|"); // The|quick|brown|fox|
By default, Split uses whitespace characters as delimiters; it’s also overloaded to
accept a params array of char or string delimiters. Split also optionally accepts a
StringSplitOptions enum, which has an option to remove empty entries: this is
useful when words are separated by several delimiters in a row.
The static Join method does the reverse of Split. It requires a delimiter and string
array:
string[] words = "The quick brown fox".Split();
string together = string.Join (" ", words); // The quick brown fox
The static Concat method is similar to Join but accepts only a params string array and
applies no separator. Concat is exactly equivalent to the + operator (the compiler, in
fact, translates + to Concat):
string sentence = string.Concat ("The", " quick", " brown", " fox");
string sameSentence = "The" + " quick" + " brown" + " fox";
c# for dummies: c sharp classes
c# for dummies: c sharp classes: Manipulating strings Because String is immutable, all the methods that “manipulate” a string ret...
c sharp classes
Manipulating strings
Because String is immutable, all the methods that “manipulate” a string return a
new one, leaving the original untouched (the same goes for when you reassign a
string variable).
Substring extracts a portion of a string:
string left3 = "12345".Substring (0, 3); // left3 = "123";
string mid3 = "12345".Substring (1, 3); // mid3 = "234";
If you omit the length, you get the remainder of the string:
string end3 = "12345".Substring (2); // end3 = "345";
Insert and Remove insert or remove characters at a specified position:
string s1 = "helloworld".Insert (5, ", "); // s1 = "hello, world"
string s2 = s1.Remove (5, 2); // s2 = "helloworld";
PadLeft and PadRight pad a string to a given length with a specified character (or a
space if unspecified):
Console.WriteLine ("12345".PadLeft (9, '*')); // ****12345
Console.WriteLine ("12345".PadLeft (9)); // 12345
If the input string is longer than the padding length, the original string is returned
unchanged.
TrimStart and TrimEnd remove specified characters from the beginning or end of a
string; Trim does both. By default, these functions remove whitespace characters
(including spaces, tabs, new lines, and Unicode variations of these):
Console.WriteLine (" abc \t\r\n ".Trim().Length); // 3
Replace replaces all occurrences of a particular character or substring:
Console.WriteLine ("to be done".Replace (" ", " | ") ); // to | be | done
Console.WriteLine ("to be done".Replace (" ", "") ); // tobedone
ToUpper and ToLower return upper- and lowercase versions of the input string. By
default, they honor the user’s current language settings; ToUpperInvariant and
ToLowerInvariant always apply English alphabet rules.
Because String is immutable, all the methods that “manipulate” a string return a
new one, leaving the original untouched (the same goes for when you reassign a
string variable).
Substring extracts a portion of a string:
string left3 = "12345".Substring (0, 3); // left3 = "123";
string mid3 = "12345".Substring (1, 3); // mid3 = "234";
If you omit the length, you get the remainder of the string:
string end3 = "12345".Substring (2); // end3 = "345";
Insert and Remove insert or remove characters at a specified position:
string s1 = "helloworld".Insert (5, ", "); // s1 = "hello, world"
string s2 = s1.Remove (5, 2); // s2 = "helloworld";
PadLeft and PadRight pad a string to a given length with a specified character (or a
space if unspecified):
Console.WriteLine ("12345".PadLeft (9, '*')); // ****12345
Console.WriteLine ("12345".PadLeft (9)); // 12345
If the input string is longer than the padding length, the original string is returned
unchanged.
TrimStart and TrimEnd remove specified characters from the beginning or end of a
string; Trim does both. By default, these functions remove whitespace characters
(including spaces, tabs, new lines, and Unicode variations of these):
Console.WriteLine (" abc \t\r\n ".Trim().Length); // 3
Replace replaces all occurrences of a particular character or substring:
Console.WriteLine ("to be done".Replace (" ", " | ") ); // to | be | done
Console.WriteLine ("to be done".Replace (" ", "") ); // tobedone
ToUpper and ToLower return upper- and lowercase versions of the input string. By
default, they honor the user’s current language settings; ToUpperInvariant and
ToLowerInvariant always apply English alphabet rules.
c# for dummies: c# for dummies
c# for dummies: c# for dummies: using System; class StringMethods { public static void Main( string[] args ) { string string1 = "hello there"; char[] charact...
c# for dummies
using System;
class StringMethods
{
public static void Main( string[] args )
{
string string1 = "hello there";
char[] characterArray = new char[ 5 ];
// output string1
Console.WriteLine( "string1: \"" + string1 + "\"" );
// loop through characters in string1 and display reversed
Console.Write( "The string reversed is: " );
for ( int i = - 1; i >= 0; i-- )
Console.Write( );
// copy characters from string1 into characterArray
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < ; i++ )
Console.Write( );
Console.WriteLine( "\n" );
} // end Main
} // end class StringMethods
// test Length property
Console.WriteLine( "Length of string1: " + string1.Length );
string1.Length
string1[ i ]
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
characterArray.Length
characterArray[ i ]
ouput
string1: "hello there"
Length of string1: 11
The string reversed is: ereht olleh
The character array is: hello
class StringMethods
{
public static void Main( string[] args )
{
string string1 = "hello there";
char[] characterArray = new char[ 5 ];
// output string1
Console.WriteLine( "string1: \"" + string1 + "\"" );
// loop through characters in string1 and display reversed
Console.Write( "The string reversed is: " );
for ( int i = - 1; i >= 0; i-- )
Console.Write( );
// copy characters from string1 into characterArray
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < ; i++ )
Console.Write( );
Console.WriteLine( "\n" );
} // end Main
} // end class StringMethods
// test Length property
Console.WriteLine( "Length of string1: " + string1.Length );
string1.Length
string1[ i ]
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
characterArray.Length
characterArray[ i ]
ouput
string1: "hello there"
Length of string1: 11
The string reversed is: ereht olleh
The character array is: hello
c# for dummies: c# for dummies
c# for dummies: c# for dummies: Strings Manipulation public static void Main( string[] args ) { Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n...
c# for dummies
Strings Manipulation
public static void Main( string[] args )
{
Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n" +
"string2 = " + "\"" + string2 + "\"\n" +
"string3 = " + "\"" + string3 + "\"\n" +
"string4 = " + "\"" + string4 + "\"\n" );
} // end Main
// end class StringConstructor
// string initialization
char[] characterArray =
{ 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
string originalString = "Welcome to C# programming!";
string string1 = originalString;
string string2 = new string( characterArray );
string string3 = new string( characterArray, 6, 3 );
string string4 = new string( 'C', 5 );
}
output
string1 = "Welcome to C# programming!"
string2 = "birth day"
string3 = "day"
string4 = "CCCCC"
public static void Main( string[] args )
{
Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n" +
"string2 = " + "\"" + string2 + "\"\n" +
"string3 = " + "\"" + string3 + "\"\n" +
"string4 = " + "\"" + string4 + "\"\n" );
} // end Main
// end class StringConstructor
// string initialization
char[] characterArray =
{ 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
string originalString = "Welcome to C# programming!";
string string1 = originalString;
string string2 = new string( characterArray );
string string3 = new string( characterArray, 6, 3 );
string string4 = new string( 'C', 5 );
}
output
string1 = "Welcome to C# programming!"
string2 = "birth day"
string3 = "day"
string4 = "CCCCC"
c# for dummies: c sharp programming
c# for dummies: c sharp programming: The System.Text.StringBuilder Type Given that the string type can be inefficient when used with reckless abandon, the .NET base class librar...
c# for dummies: c sharp programming
c# for dummies: c sharp programming: The System.Text.StringBuilder Type Given that the string type can be inefficient when used with reckless abandon, the .NET base class librar...
c sharp programming
The System.Text.StringBuilder Type
Given that the string type can be inefficient when used with reckless abandon, the .NET base class
libraries provide the System.Text namespace. Within this (relatively small) namespace lives a class
named StringBuilder. Like the System.String class, the StringBuilder defines methods that allow you
to replace or format segments, for example. When you wish to use this type in your C# code files, your
first step is to make sure the following namespace is imported into your code file:
// StringBuilder lives here!
using System.Text;
What is unique about the StringBuilder is that when you call members of this type, you are directly
modifying the object’s internal character data (making it more efficient), not obtaining a copy of the data
in a modified format. When you create an instance of the StringBuilder, you can supply the object’s
initial startup values via one of many constructors. If you are new to the topic of constructors, simply
understand that constructors allow you to create an object with an initial state when you apply the new
keyword. Consider the following usage of StringBuilder:
static void FunWithStringBuilder()
{
Console.WriteLine("=> Using the StringBuilder:");
StringBuilder sb = new StringBuilder("**** Fantastic Games ****");
sb.Append("\n");
sb.AppendLine("Half Life");
sb.AppendLine("Beyond Good and Evil");
sb.AppendLine("Deus Ex 2");
sb.AppendLine("System Shock");
Console.WriteLine(sb.ToString());
sb.Replace("2", "Invisible War");
Console.WriteLine(sb.ToString());
Console.WriteLine("sb has {0} chars.", sb.Length);
Console.WriteLine();
}
Here we have constructed a StringBuilder set to the initial value "**** Fantastic Games ****". As
you can see, we are appending to the internal buffer and are able to replace or remove characters at will.
By default, a StringBuilder is only able to initially hold a string of 16 characters or fewer (but will expand
automatically if necessary); however, this default starting value can be changed via an additional
constructor argument.
Given that the string type can be inefficient when used with reckless abandon, the .NET base class
libraries provide the System.Text namespace. Within this (relatively small) namespace lives a class
named StringBuilder. Like the System.String class, the StringBuilder defines methods that allow you
to replace or format segments, for example. When you wish to use this type in your C# code files, your
first step is to make sure the following namespace is imported into your code file:
// StringBuilder lives here!
using System.Text;
What is unique about the StringBuilder is that when you call members of this type, you are directly
modifying the object’s internal character data (making it more efficient), not obtaining a copy of the data
in a modified format. When you create an instance of the StringBuilder, you can supply the object’s
initial startup values via one of many constructors. If you are new to the topic of constructors, simply
understand that constructors allow you to create an object with an initial state when you apply the new
keyword. Consider the following usage of StringBuilder:
static void FunWithStringBuilder()
{
Console.WriteLine("=> Using the StringBuilder:");
StringBuilder sb = new StringBuilder("**** Fantastic Games ****");
sb.Append("\n");
sb.AppendLine("Half Life");
sb.AppendLine("Beyond Good and Evil");
sb.AppendLine("Deus Ex 2");
sb.AppendLine("System Shock");
Console.WriteLine(sb.ToString());
sb.Replace("2", "Invisible War");
Console.WriteLine(sb.ToString());
Console.WriteLine("sb has {0} chars.", sb.Length);
Console.WriteLine();
}
Here we have constructed a StringBuilder set to the initial value "**** Fantastic Games ****". As
you can see, we are appending to the internal buffer and are able to replace or remove characters at will.
By default, a StringBuilder is only able to initially hold a string of 16 characters or fewer (but will expand
automatically if necessary); however, this default starting value can be changed via an additional
constructor argument.
c# for dummies: c sharp programming
c# for dummies: c sharp programming: Strings Are Immutable One of the interesting aspects of System.String is that once you assign a string object with its initial value, the ...
c sharp programming
Strings Are Immutable
One of the interesting aspects of System.String is that once you assign a string object with its initial
value, the character data cannot be changed. At first glance, this might seem like a flat-out lie, given that
we are always reassigning strings to new values and because the System.String type defines a number of
methods that appear to modify the character data in one way or another (such as uppercasing and
lowercasing). However, if you look more closely at what is happening behind the scenes, you will notice
the methods of the string type are, in fact, returning you a brand-new string object in a modified
format.
static void StringsAreImmutable()
{
// Set initial string value.
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);
// Uppercase s1?
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);
// Nope! s1 is in the same format!
Console.WriteLine("s1 = {0}", s1);
}
One of the interesting aspects of System.String is that once you assign a string object with its initial
value, the character data cannot be changed. At first glance, this might seem like a flat-out lie, given that
we are always reassigning strings to new values and because the System.String type defines a number of
methods that appear to modify the character data in one way or another (such as uppercasing and
lowercasing). However, if you look more closely at what is happening behind the scenes, you will notice
the methods of the string type are, in fact, returning you a brand-new string object in a modified
format.
static void StringsAreImmutable()
{
// Set initial string value.
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);
// Uppercase s1?
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);
// Nope! s1 is in the same format!
Console.WriteLine("s1 = {0}", s1);
}
c# for dummies: c sharp programming
c# for dummies: c sharp programming: Strings and Equality As fully explained in Chapter 4, a reference type is an object allocated on the garbage-collected managed heap. By d...
c sharp programming
Strings and Equality
As fully explained in Chapter 4, a reference type is an object allocated on the garbage-collected managed
heap. By default, when you perform a test for equality on reference types (via the C# == and !=
operators), you will be returned true if the references are pointing to the same object in memory.
However, even though the string data type is indeed a reference type, the equality operators have been
redefined to compare the values of string objects, not the object in memory to which they refer.
static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();
// Test these strings for equality.
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 == HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
Console.WriteLine();
}
The C# equality operators perform a case-sensitive, character-by-character equality test on string
objects. Therefore, "Hello!" is not equal to "HELLO!", which is different from "hello!". Also, keeping the
connection between string and System.String in mind, notice that we are able to test for equality using
the Equals() method of String as well as the baked-in equality operators. Finally, given that every string
literal (such as "Yo") is a valid System.String instance, we are able to access string-centric functionality
from a fixed sequence of characters.
As fully explained in Chapter 4, a reference type is an object allocated on the garbage-collected managed
heap. By default, when you perform a test for equality on reference types (via the C# == and !=
operators), you will be returned true if the references are pointing to the same object in memory.
However, even though the string data type is indeed a reference type, the equality operators have been
redefined to compare the values of string objects, not the object in memory to which they refer.
static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();
// Test these strings for equality.
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 == HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
Console.WriteLine();
}
The C# equality operators perform a case-sensitive, character-by-character equality test on string
objects. Therefore, "Hello!" is not equal to "HELLO!", which is different from "hello!". Also, keeping the
connection between string and System.String in mind, notice that we are able to test for equality using
the Equals() method of String as well as the baked-in equality operators. Finally, given that every string
literal (such as "Yo") is a valid System.String instance, we are able to access string-centric functionality
from a fixed sequence of characters.
c# for dummies: c sharp programming
c# for dummies: c sharp programming: String Concatenation string variables can be connected together to build larger strings via the C# + operator. As you may know, this tec...
c sharp programming
String Concatenation
string variables can be connected together to build larger strings via the C# + operator. As you may
know, this technique is formally termed string concatenation. Consider the following new helper
function:
static void StringConcatenation()
{
Console.WriteLine("=> String concatenation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
Console.WriteLine(s3);
Console.WriteLine();
}
string variables can be connected together to build larger strings via the C# + operator. As you may
know, this technique is formally termed string concatenation. Consider the following new helper
function:
static void StringConcatenation()
{
Console.WriteLine("=> String concatenation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
Console.WriteLine(s3);
Console.WriteLine();
}
c# for dummies: string manipulation
c# for dummies: string manipulation: Basic String Manipulation Working with the members of System.String is as you would expect. Simply declare a strin...
string manipulation
Basic String Manipulation
Working with the members of System.String is as you would expect. Simply declare a string variable
and make use of the provided functionality via the dot operator. Be aware that a few of the members of
System.String are static members and are, therefore, called at the class (rather than the object) level.
Assume you have created a new Console Application project named FunWithStrings. Author the
following method, which should be called from within Main():
static void BasicStringFunctionality()
{
Console.WriteLine("=> Basic String functionality:");
string firstName = "Freddy";
Console.WriteLine("Value of firstName: {0}", firstName);
Console.WriteLine("firstName has {0} characters.", firstName.Length);
Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
Console.WriteLine("firstName contains the letter y?: {0}",
firstName.Contains("y"));
Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
Console.WriteLine();
}
Not too much to say here, as this method simply invokes various members, such as ToUpper() and
Contains(), on a local string variable to yield various formats and transformations.
Working with the members of System.String is as you would expect. Simply declare a string variable
and make use of the provided functionality via the dot operator. Be aware that a few of the members of
System.String are static members and are, therefore, called at the class (rather than the object) level.
Assume you have created a new Console Application project named FunWithStrings. Author the
following method, which should be called from within Main():
static void BasicStringFunctionality()
{
Console.WriteLine("=> Basic String functionality:");
string firstName = "Freddy";
Console.WriteLine("Value of firstName: {0}", firstName);
Console.WriteLine("firstName has {0} characters.", firstName.Length);
Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
Console.WriteLine("firstName contains the letter y?: {0}",
firstName.Contains("y"));
Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
Console.WriteLine();
}
Not too much to say here, as this method simply invokes various members, such as ToUpper() and
Contains(), on a local string variable to yield various formats and transformations.
Tuesday, 13 November 2012
c# for dummies: c sharp programming
c# for dummies: c sharp programming: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringManipulationPost { class Program ...
c sharp programming
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string[] strings = { "started", "starting", "ended", "ending" };
// test every string to see if it starts with "st"
for ( int i = 0; i < strings.Length; i++ )
if (strings[ i ].StartsWith( "st" ) )
Console.WriteLine( "\"" + strings[ i ] + "\"" +
" starts with \"st\"" );
Console.WriteLine();
// test every string to see if it ends with "ed"
for ( int i = 0; i < strings.Length; i++ )
if ( strings[ i ].EndsWith( "ed" ) )
Console.WriteLine( "\"" + strings[ i ] + "\"" +
" ends with \"ed\"" );
Console.WriteLine();
//strings[ i ].StartsWith( "st" )
//strings[ i ].EndsWith( "ed" )
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string[] strings = { "started", "starting", "ended", "ending" };
// test every string to see if it starts with "st"
for ( int i = 0; i < strings.Length; i++ )
if (strings[ i ].StartsWith( "st" ) )
Console.WriteLine( "\"" + strings[ i ] + "\"" +
" starts with \"st\"" );
Console.WriteLine();
// test every string to see if it ends with "ed"
for ( int i = 0; i < strings.Length; i++ )
if ( strings[ i ].EndsWith( "ed" ) )
Console.WriteLine( "\"" + strings[ i ] + "\"" +
" ends with \"ed\"" );
Console.WriteLine();
//strings[ i ].StartsWith( "st" )
//strings[ i ].EndsWith( "ed" )
Console.ReadLine();
}
}
}
c# for dummies: c sharp classes
c# for dummies: c sharp classes: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringManipulationPost { class Program ...
c sharp classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string string1 = "hello";
string string2 = "good bye";
string string3 = "Happy Birthday";
string string4 = "happy birthday";
Console.WriteLine( "string1 = \"" + string1 + "\"" +
"\nstring2 = \"" + string2 + "\"" +
"\nstring3 = \"" + string3 + "\"" +
"\nstring4 = \"" + string4 + "\"\n" );
// test for equality using Equals method
if ( string1.Equals( "hello" ) )
Console.WriteLine( "string1 equals \"hello\"" );
else
Console.WriteLine( "string1 does not equal \"hello\"" );
// test for equality with ==
if ( string1 == "hello" )
Console.WriteLine( "string1 equals \"hello\"" );
else
Console.WriteLine( "string1 does not equal \"hello\"" );
// test for equality comparing case
if ( string.Equals( string3, string4 ) ) // static method
Console.WriteLine( "string3 equals string4" );
else
Console.WriteLine( "string3 does not equal string4" );
string1.Equals( "hello" );
//string1 == "hello";
string.Equals( string3, string4 );
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string string1 = "hello";
string string2 = "good bye";
string string3 = "Happy Birthday";
string string4 = "happy birthday";
Console.WriteLine( "string1 = \"" + string1 + "\"" +
"\nstring2 = \"" + string2 + "\"" +
"\nstring3 = \"" + string3 + "\"" +
"\nstring4 = \"" + string4 + "\"\n" );
// test for equality using Equals method
if ( string1.Equals( "hello" ) )
Console.WriteLine( "string1 equals \"hello\"" );
else
Console.WriteLine( "string1 does not equal \"hello\"" );
// test for equality with ==
if ( string1 == "hello" )
Console.WriteLine( "string1 equals \"hello\"" );
else
Console.WriteLine( "string1 does not equal \"hello\"" );
// test for equality comparing case
if ( string.Equals( string3, string4 ) ) // static method
Console.WriteLine( "string3 equals string4" );
else
Console.WriteLine( "string3 does not equal string4" );
string1.Equals( "hello" );
//string1 == "hello";
string.Equals( string3, string4 );
Console.ReadLine();
}
}
}
c# for dummies: c sharp programming
c# for dummies: c sharp programming: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringManipulationPost { class Program ...
c sharp programming
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string string1 = "hello there";
char[] characterArray = new char[ 5 ];
// output string1
Console.WriteLine( "string1: \"" + string1 + "\"" );
// loop through characters in string1 and display reversed
Console.Write( "The string reversed is: " );
for ( int i = - 1; i >= 0; i-- )
Console.Write( string1[i] );
// copy characters from string1 into characterArray
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < characterArray.Length ; i++ )
Console.Write(characterArray[i]);
Console.WriteLine( "\n" );
// test Length property
Console.WriteLine( "Length of string1: " + string1.Length );
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
string string1 = "hello there";
char[] characterArray = new char[ 5 ];
// output string1
Console.WriteLine( "string1: \"" + string1 + "\"" );
// loop through characters in string1 and display reversed
Console.Write( "The string reversed is: " );
for ( int i = - 1; i >= 0; i-- )
Console.Write( string1[i] );
// copy characters from string1 into characterArray
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < characterArray.Length ; i++ )
Console.Write(characterArray[i]);
Console.WriteLine( "\n" );
// test Length property
Console.WriteLine( "Length of string1: " + string1.Length );
Console.ReadLine();
}
}
}
c# for dummies: c# programing
c# for dummies: c# programing: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringManipulationPost { class Program ...
c# programing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
char[] characterArray =
{ 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
string originalString = "Welcome to C# programming!";
string string1 = originalString;
string string2 = new string( characterArray );
string string3 = new string( characterArray, 6, 3 );
string string4 = new string( 'C', 5 );
Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n"+
"string2 = " + "\"" + string2 + "\"\n" +
"string3 = " + "\"" + string3 + "\"\n" +
"string4 = " + "\"" + string4 + "\"\n" );
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationPost
{
class Program
{
static void Main(string[] args)
{
char[] characterArray =
{ 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
string originalString = "Welcome to C# programming!";
string string1 = originalString;
string string2 = new string( characterArray );
string string3 = new string( characterArray, 6, 3 );
string string4 = new string( 'C', 5 );
Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n"+
"string2 = " + "\"" + string2 + "\"\n" +
"string3 = " + "\"" + string3 + "\"\n" +
"string4 = " + "\"" + string4 + "\"\n" );
Console.ReadLine();
}
}
}
Subscribe to:
Posts (Atom)