C# String with Programming Examples
C# String:
C# String with Programming Examples:-There are two classes in C# with a clear division of tasks for working with strings: String and StringBuilder. Typically, in C#, strings are created as objects of the String class. The String class is easy to use and equipped with many useful methods. It is also thread-safe and so far into the Language integrates that strings appear almost like a primitive data type. However, this has convenience a price: String objects are immutable, i.e. once they have been created, the String object represented by the string can no longer be changed. For cases in which strings are built up dynamically piece by piece or multiple insertions and Therefore, there is a second class: StringBuilder.
C# String generation:
Strings are represented in C# by objects of the String class. The class String only occurs rarely in direct appearance, because the strings are so well integrated into the language that they can hardly be seen as objects are to be perceived. String variables are usually assigned the keyword instead of the type of the String class string defined. And instead of using new, the string objects themselves are preferably indirectly Literal generates:
1 2 3 |
string str1 = ""; string str2 = "Hello"; |
A string object is generated internally for each string literal. The references to the String objects are stored in the string variables. The above syntax is not just a convenient alternative to string generation using new and a constructor call. For empty strings or strings from literals, it is even the only viable option, because the class c# String does not provide any constructors for these tasks. The public constructors of C# String serve exclusively to generate strings from characters, character arrays and in unsafe code also from pointers to characters or character codes.
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 |
// Generation of a string of 20 characters (here hyphens): string line = new String ('-', 20); Console.WriteLine (line); // Generation of a string from an array of characters: char [] c = {'a', 'b', 'c'}; string abc = new String (c); // Generation of a string from an array of character codes: unsafe { String word = null; sbyte [] codes = new sbyte [] {0x43, 0x23, 0x00}; fixed (sbyte * pCodes = codes) { word = new String (pCodes); } ... } String str = new String (); // Error in C# because there are no matching ones String str = new String ("Hello"); // Constructors available |
C# String literals:
String literals are enclosed in double quotation marks.
1 |
"I am a string!"; |
Each string literal is followed by an object of the String class in C#.
C# String Escape sequences:
You can use escape sequences within a C# string, to insert non-displayable characters such as line breaks or tabs or to display, that a trailing function character such as the double quotation mark or the escape character is not to be regarded as a function sign, but as a literal sign:
1 2 3 4 5 |
"Error! \ A"; "The answer is: \" No \ ""; "C: \\ Directory"; |
Program Example: how to use a backslash in c# Escape sequence:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string text = "My name is \"Fawad khan \" ceo of Programming digest."; string str = "abc\\xyz"; string dir = "\\\\location\\ d\\folder"; Console.WriteLine(text); Console.WriteLine(str); Console.WriteLine(dir); Console.ReadKey(); } } |
Output:
1 2 3 4 5 |
My name is "Fawad khan " ceo of Programming digest. abc\xyz \\location\ d\folder |
@ Literals:
If you precede a string literal with the @ sign, the literal is not escaped parsed. Instead, everything is between the opening and closing quotation marks interpreted as literal characters – including any tabs or line breaks!
@ Literals simplify the specification of directory paths
1 |
@ "C: \ Directory"; |
as well as the formatting of strings using indentations and breaks:
1 2 3 4 5 6 7 8 9 10 11 |
@ " x y ----------- 2 4 3 9 "; |
program Example: how to @ in C# escape sequence:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string str = @"My name is \\Fawad khan"; string dir = @"\\location\\ d\\folder"; Console.WriteLine(str); Console.WriteLine(dir); Console.WriteLine(email); Console.ReadKey(); } } |
Output:
1 2 3 4 5 |
My name is \\Fawad khan \\location\\ d\\folder abc@xyz.com |
Line breaks:
In principle, string literals cannot span several lines:
1 2 3 |
string str = "String literals must not have multiple lines are distributed. "; // ERROR |
If you precede the literal with the @ sign, you can write it over multiple lines, but you can then the breaks and the indenting spaces become part of the string literal. Is this not desired, so the string literal should only be distributed over several Lines are distributed, split the text into several C# string literals, which you connect with the + operator:
1 2 3 |
string str = "String literals must not exceed" + "multiple lines are distributed."; // correct |
Conversely, if you want to incorporate breaks in a string without breaking the string in the source code, insert the break in the form of the escape sequence \ n:
1 |
string str = "The first line. \ nThe second line."; |
C# Strings Pooling:
String literals are generated internally as string objects. It is therefore possible, for example, for string Literals to call the instance methods defined in C# String:
1 |
string str = "Hello" .ToUpper(); |
However, a separate object is not necessarily created for each string literal. If the compiler determines that there is already an object for a requested literal, no new object is created, but the Reference to the existing object returned (string pooling). Programming with strings will thus more efficient and more memory-saving.
1 2 3 4 5 6 7 |
string s1 = "Hello"; // Creates a new string object and stores it in s1 // the reference to this object string s2 = "Hello"; // Stores the reference to the one generated above in s2 // String object too |
String objects created by one of the constructors of the String class or as the result of one of the String methods are returned, do not take part in the internal pooling by default. But you can use the String method Intern() to generate an »interned« twin string:
1 2 3 4 5 |
string str1 = "Original"; // interned string str2 = String.Concat ("Origina" + "l"); // not interned string str3 = String.Intern (str2); // interned, same reference as str1 |
You can use the IsInterned() method to check whether a string is participating in internal pooling.
C# String comparisons:
Strings are always compared lexicographically, that is, the two strings are compared from the beginning scroll backwards and compare character by character. If all characters are identical, the decides Length of the strings.
Equality and inequality:
You can determine the equality or inequality of two strings with the operators == and! = Or with the Determine the Equals() C# string method. Both the operators and the Equals() methods strictly compare the characters in the strings based on their ordinal numbers in Unicode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
string password; Console.Write ("Enter password:"); password = Console.ReadLine (); if (password! = "Fawadkhan") // Alternative:! password.Equals ("Fawadkhan") { Console.WriteLine ("Sorry, no access!"); return; } |
Size comparisons:
For C# string comparisons, which also involve a lexicographical classification of the compared strings the instance method CompareTo() and the static method Compare() are available.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
string strA = "A"; string strB = "B"; if (strA.CompareTo (strB) <0) { ... } if (String.Compare (strA, strB) <0) { ... } |
Both methods return an integer value less than, equal to or greater than 0 as a result:
- <0, strA smaller strB
- 0, strA equal strB
- 0, strA greater strB
Both methods do not only compare according to the position of the characters in Unicode, but also taking into account of the alphabet and linguistic peculiarities of the current culture (classification of umlauts, Lower case letters are smaller than upper case letters etc.). This also applies to the overloaded versions from Compare():
1 |
static int Compare (strA, strB, ignoreGK) |
Is not case-sensitive if true is passed as the third argument.
1 |
static int Compare (strA, strB, comparison type) |
Takes a member of the StringComparison enumeration as the third argument:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
enum StringComparison { CurrentCulture, // comparison taking into account the current culture CurrentCultureIgnoreCase, // as above, but with no distinction between // Large and lower case InvariantCulture, // compares taking into account. of the invariant culture 2 InvariantCultureIgnoreCase, // as above, but without differentiating between // Large and lower case Ordinal, // Compares according to Unicode OrdinalCultureIgnoreCase // as above, but with no distinction between // Large and lower case } |
Compares the string strA starting at position indexA with the string strB starting at position indexB. It will maximum length characters compared.
1 2 3 4 5 6 7 |
string strA = "privy councilor"; string strB = "betrayal"; String.Compare (strA, 5, strB, 2, strA.Length) // returns value <0 String.Compare (strA, 6, strB, 3, strA.Length) // returns 0 |
Culture-independent size comparisons in c#:
To compare strings purely according to the Unicode of their characters without considering cultural peculiarities The easiest way to use the CompareOrdinal() method is:
1 2 3 4 5 6 7 8 9 |
string strA = "A"; string strB = "a"; if (String.CompareOrdinal (strA, strB) <0) // false, since the uppercase letters in Unicode {// are coded in front of the lowercase letters } |
There is only a single overload of the CompareOrdinal() method to compare substrings can:
1 |
static int CompareOrdinal (strA, indexA, strB, indexB, length) |
Compares the string strA starting at position indexA with the string strB starting at position indexB. It will maximum length characters compared.
C# String manipulations:
Programming with strings is of course not limited to creating and comparing Strings. Sequencing, splitting, converting and analyzing strings are at least the same important operations for which the programmer – and not without good reason – has appropriate support in the Hopes to find standard library. In C#, most of this functionality is in the String class summarized.
Stringing together:
With the + operator you can combine two string objects to form a new string object.
1 2 3 4 5 |
string s1 = "Hello"; string s2 = "programmer"; string s3 = s1 + s2; // "Hello programmer" |
If one of the operands of the + operator is not a string, it is converted to a string. This makes it easier for example the integration of numbers in text output:
1 2 3 4 5 |
int sec; ... Console.WriteLine ("It has" + sec + "seconds passed."); |
static string Concat():
The alternative to the + operator is the static string method Concat(). It is overloaded several times and allows the programmer to choose between two, three, four or an array of strings (or object instances3) to concatenate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Concatenate three strings with concat (string, string, string) // Result: name = "Peterson, Pete" string firstName = "Pete"; string secondName = "Peterson"; string name = String.Concat (secondName, ",", firstName); // Concatenate five numbers into a string with concat (Object []) // Result: values = "12345" Object [] objs = new Object [] {1, 2, 3, 4, 5}; string values = String.Concat (objs); |
Convert arrays to strings:
Sometimes it is very useful to output the contents of an array as a string – even if only for the Debug the program. Whoever hopes, however, will only use the one offered by the Array class for this purpose Having to call the ToString() method will be disappointed: The Array class takes over simply the implementation inherited from Object, i. H. the type of the array object is returned. For a useful string representation of the array content, the programmer has to do it himself by converting the individual array elements into strings and outputting them. The following fragment demonstrates how an array is converted into a string array, which is then converted using String.Join() is prepared for output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// convert double array to string array double [] numbers = new double [] {1.011, 2.555, 33.0, 4.0001}; String [] sArray = new String [numbers.Length]; for (int i = 0; i <numbers.Length; ++ i) { sArray [i] = String.Format ("{0: F2}", numbers [i]); } // Convert string array to string and insert separator Console.WriteLine ("join: {0}", String.Join ("", sArray)); |
In C# 2.0, as an alternative to converting any array to a string array, you can use the Use Array.ConvertAll() and a converter. The latter is a generic one Delegate to whom you can specify the source type, the target type and the Transfer method previously defined by you.
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 |
class ArrayToString {// Method for converting the double values into strings public static string DoubleToString (double a) { return String.Format ("{0: F2}", a); } static void Main () { double [] numbers = new double [] {1.011, 2.555, 33.0, 4.0001}; // convert double array into string array: via converter delegate String [] sArray = Array.ConvertAll (numbers, new Converter <double, string> (DoubleToString)); // Convert string array to string and insert separator Console.WriteLine ("join: {0}", String.Join ("", sArray)); } } } |
C# String Insert, delete, replace:
The Insert() method is used to insert into a string. The method takes the Insertion position and the string to be inserted. The new string is returned as the result. The Insertion position is equal to the zero-based index of the character in the string before which it is to be inserted.
1 2 3 4 5 |
string str = "134"; string result = str.Insert(1, "2"); Console.WriteLine(result); // output 1234 |
There is no separate method for appending to a string; just pass the length of the original string to Insert():
1 2 3 4 |
string str = "Fawad"; string str1 = str.Insert(str.Length, " Khan"); // out put Fawad khan" Console.WriteLine(str1); |
To delete, use the Remove() method, which is the zero-based index of the first one to delete Character and the number of characters to be deleted:
1 2 3 4 5 |
string str = "my name is fawad khan"; string str1 = str.Remove(0, 10); // output: fawad khan Console.WriteLine(str1); |
With Replace() you can search the string for a given string and replace it with a have the second string replaced:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// only replace 1st occurrence string text = "aabbaabb"; string sOld = "bb"; string sNew = "AA"; int pos = text.IndexOf (sOld); // Detect occurrences text = text.Remove (pos, sOld.Length); // delete occurrences text = text.Insert (pos, sNew); // insert new string -> aaAAaabb |
Searching in C# String:
You can use the IndexOf() and LastIndexOf() methods to search for the first or last occurrence of a Search for characters or strings. The zero-based index or the value –1 is returned, if no occurrence was found.
1 2 3 4 5 6 7 8 9 |
string str = "Papperlapapp"; int fi = str.IndexOf("ap"); int li = str.LastIndexOf("ap"); Console.WriteLine(fi); // 1 Console.WriteLine(li); // 9 |
You can further configure the search by specifying the position from which to search in the string how many characters are to be searched (only in combination with the specification of the start position) or how should be compared (only when searching for strings).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
IndexOf (char z, int start) // Search from position start IndexOf (string s, int start) IndexOf (char z, int start, int length) // Searches only long characters IndexOf (string s, int start, int length) IndexOf (string s, StringComparison comparison mode) // Comparison according to IndexOf (string s, int start, StringComparison comparison mode) // comparison mode IndexOf (string s, int start, int length, StringComparison comparison mode) |
It is also possible to search for the first (last) occurrence of one of several characters. The Methods that do this are called IndexOfAny() and LastIndexOfAny(). Pass a char Array with the characters to be searched for and – optionally – the start position, including length specification if necessary.
C# String assembly and Disassembly:
The String class supports two ways to decompose a string: You can use Substring() to create a Cut out a substring or split the string into an array of substrings with Split(). For the reverse process there is the method Join(), which the elements of a string array to a string and the Concat() method discussed above.
Substring()
1 2 3 |
Substring (int startIndex, int length) Substring (int startIndex) |
With Substring() you can extract a substring from a string. Pass the as arguments zero-based index of the first character to be extracted and how many characters are extracted should be. If you only pass the start index, the rest of the original string is returned. The example demonstrates the extraction of the first five characters from a string:
1 2 3 |
string str = "Fawad khan"; string str1 = str.Substring(0,5); // Extracts "iron" Console.WriteLine(str1); // output Fawad |
Split()
1 2 3 4 5 6 7 8 9 10 11 |
Split (char [] separator) Split (char [] separator, int number) Split (char [] separator, StringSplitOptions empty elements) Split (char [] separator, int number, StringSplitOptions empty elements) Split (string [] separating strings, StringSplitOptions empty elements) Split (string [] separating strings, int number, StringSplitOptions empty elements) |
With Split() you can split a single string into an array of substrings. The predetermined breaking points which the string is split up, pass as an array of characters or strings. If you only have a single To define separators, just pass a single element array. If you are for the first Passed argument null, will be split at the newline character ‘\ n’. Important: The separators are sorted out in the course of the extraction, i.e. they cannot be found in the extracted substrings. If several separators follow one another (or are they at the beginning or end of the string) this does this to insert empty strings into the result array. However, you can change this behavior by passing StringSplitOptions.RemoveEmptyEntries as an additional argument.
You can also specify the maximum number of substrings to be written into the result array. The last substring then contains the rest of the string (including any separators it may contain).
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 |
// Break down text into individual words using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string str = "my name is fawad khan"; string [] words = str.Split(new Char [] {' '}); foreach (string s in words) { Console.WriteLine (s); } Console.ReadKey(); } } |
Output:
1 2 3 4 5 6 7 8 9 |
my name is fawad khan |
So that character strings made up of punctuation marks and spaces do not lead to the extraction of empty strings, pass as an additional Argument StringSplitOptions.RemoveEmptyEntries:
1 2 3 |
words = str.Split (new Char [] {'', ',', '.', '?', '!', ';', ':'}, StringSplitOptions.RemoveEmptyEntries); |
Join()
1 2 3 |
Join (string fugue, string [] elements) Join (string fugue, string [] elements, int start, int number) |
Join() joins the elements of a string array into a single string. The first argument is
a string that is inserted as a joint between two consecutive elements. Optionally can You determine which is the first array element to be used and how many elements are combined in total should be.
1 2 3 4 5 6 7 |
string [] words = new String [] {"The", "Achiever", "is", "as", "Human", "often", "a", "failure"}; string str = String.Join ("", words); Console.WriteLine ("-" + str + "-"); |
Trim and padding
When processing texts electronically, the problem often arises that at the ends of a Strings, unpleasant white space characters can appear, which during further processing (joining, Output, compare) cause problems. The String class therefore defines three methods with which Use spaces (whitespace, line break, tabs, etc.) from the beginning, end or easily remove both sides of a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Trim () // Removes whitespace from both ends of the string Trim (char [] characters) // Removes all characters passed in the array TrimStart (char [] character) // Removes all characters passed in the array from the beginning TrimEnd (char [] character) // Removes all characters passed in the array from the end The following example removes unwanted whitespace characters from user input: Console.Write ("Please enter your name:"); string name = Console.ReadLine (); name = name.Trim (); Console.WriteLine ("-" + name + "-"); |
The counterpart to the trim methods are the padding methods, which you can use at the beginning or at the end pad a string with spaces (or a character of your choice).
1 2 3 4 5 6 7 |
PadLeft (int total length) // fills the left PadLeft (int total length, char fill character) PadRight (int total length) // pads on the right PadRight (int total length, char fill character) |
The total length indicates how many characters the result string should have (original number Characters in the original string plus filler characters).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// right justified output string [] customers = new string [] {"fawad", "khan", "shaista"}; foreach (string s in customers) { Console.WriteLine (see PadLeft (20, '.')); } Output: ................ fawad .............khan ............ shaista |
C# String Converting:
If strings are not in the form required for further processing, they must be converted become. There are predefined methods for the most important conversions.
Upper case and lower case
Differences in upper and lower case can cause a lot of trouble, especially when comparing strings. If you are only interested in individual comparisons, you can instruct Compare() to be case-sensitive ignore. Multiple comparisons are required or is case-sensitive for other reasons, you can use the relevant strings use the methods ToUpper() or ToLower() to convert them to upper or lower case.
1 2 3 4 5 |
string str = "aAbccD"; Console.WriteLine(str.ToUpper()); // "AABCCD" Console.WriteLine(str.ToLower()); // "aabccd" |
Conversion from and to other data types in c# strings:
You can convert primitives and some other predefined Convert data types to strings.
Conversion to | Methode |
bool | Convert.ToBoolean(string) |
byte | Convert.ToByte(string) |
char | Convert.ToChar (string)
Returns the first character in the string |
DateTime | Convert.ToDateTime(string) |
decimal | Convert.ToDecimal(string) |
double | Convert.ToDouble(string) |
short | Convert.ToInt16(string) |
int | Convert.ToInt32(string) |
long | Convert.ToInt64(string) |
float | Convert.ToSingle(string) |
If the format of the passed string does not allow conversion, a FormatException exception is raised triggered. When converting to number types, OverflowException exceptions can also occur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
int number; Console.Write ("Please enter a number:"); string input = Console.ReadLine (); try { number = Convert.ToInt32 (input); Console.WriteLine ("\ n" + number); } catch (exception e) { Console.WriteLine (e.Message); } |
In the opposite direction, the top base class Object inherits the ToString() method, which is found in numerous Framework classes is overwritten.
Conversion to character array:
1 2 3 |
ToCharArray () ToCharArray (int start, int length) |
Writes the characters of a string to a char array.
Access individual characters:
You can use the [] operator to access specific characters in the string. You can see the characters but only read, not overwrite.
1 2 3 4 5 |
string str = "Welcome"; int pos = str.IndexOf ('o'); char c = str [pos]; |
Copy:
In C#, the easiest way to copy strings is to use the assignment operator or the Clone() method:
1 2 3 4 5 |
string str1 = "Welcome"; string str2 = str1; string str3 = (string) str1.Clone(); |
No real copy is created in this way, only the reference to the string copied, but since String objects are immutable, it usually makes no difference. For cases in which a real copy is necessary (e.g. because the C# string have been manipulated in an unsafe context or should not participate in internal pooling), there is the static method Copy():
1 |
string str4 = String.Copy (str1); |
Finally, there is the possibility of copying part of a string into a character array with CopyTo(). As Arguments pass the index of the first character to be copied, the character array, and the index of the first character in the array to be overwritten and the total number of characters to be copied.
1 2 3 |
char [] str5 = {'-', '-', '-', '-', '-', '-'}; str1.CopyTo (4, str5, 2, 4); // str5 becomes -com- |
C# String Class methods with Description:
Methods of the String class | Description |
Length int | Returns the number of characters contained in the string:
string s = “Hi”; int lg = s.Length; lg now contains 2. |
Int Compare(string s1, string s2); | Static method that compares the strings s1 and s2. Compare holds correctly account of the weight of our accented letters. Compare returns 0 if both strings contain exactly the same characters, a negative value if s1 is less to s2 and a positive value if s1 is greater than s2.
string s1 = “ferret”, s2 = “elephant”; int n = String.Compare (s1, s2); n here contains a positive value because f, the first letter of a ferret, has a greater weight. Recall that if the operators == and! = Have been redefined in the String class, this is not the case for the <, <=,> and> = operators. See the note at the end of this table concerning the comparison times according to of the method used. |
Int Compare(string, string, bool ignoreCase); | The third argument indicates whether to ignore the case (i.e. compare without distinguish between lowercase and uppercase). |
int CompareTo (string); | Similar to Compare but it is a non-static method of the class.
string s1 = “ferret”, s2 = “elephant”; int n = s1.CompareTo (s2); n contains 1 (it is the fact that n contains a positive value that is important). |
String Concat(string s1, string s2); | Static method of the class returning a string which is the concatenation of s1 and of s2.
string s1 = “ABC”, s2 = “123”, s; s = String.Concat (s1, s2); s contains “ABC123” while s1 and s2 are unchanged (when a function of the String class is applied to an object, this object is never directly modified). |
bool Contains(string); | Returns true if the string the method is on contains :
string ani = “calf, cow, pig”; if (ani.Contains (“cow”)) ….. |
string Copy(string s); | Static method of the class that returns a copy of a string:
string s1 = “ABC”, s2; s2 = String.Copy (s1); s2 now contains “ABC”. We could have written more simply (since the operator = applied to a string makes a real copy): s2 = s1; |
bool EndsWith(string s); | Returns true if the string to which the operation is carried out ends with the string s.
string s = “Hello”; bool b = s.EndsWith (“day”); b is false. |
String Format(string, from one to four arguments); | Static method of the class which formats a character string.
|
int IndexOf (char c); | Returns the position of the character c in the string to which the operation relates (0 for the first position and –1 if it was not found). The LastIndexOf function is similar to IndexOf, except the string is scanned from right to left starting at the end. To check if the character c contains a number, we can write (but rather see the methods of the Char class, both simpler and more efficient):
if (“0123456789” .IndexOf (c)! = -1) ….. |
Int IndexOf( char c, int pos); | Same thing but the search starts at the pos-th character of the string:
string s = “Hello”; int n = s.IndexOf (‘o’, 2); n contains 4 (search for the letter o starting from the third character). |
int IndexOf(string s); | Like the first form but searches for a string rather than a character. |
Int IndexOf( string s, int pos); | Like the second form but search for a string. |
String Insert(int pos, string s); | Inserts the string s in the string to which the operation relates (insertion from the position in this last string):
string s = “ABCD”, s2 = “123”; s.Insert (1, s2); s now contains “A123BCD”. |
string PadLeft(int n); | Returns a string made up of n Length spaces followed by the string on which carries the function:
string s = “Hi”, s1; s1 = s.PadLeft (8); s1 contains “Hi”. |
String PadLeft(int n, char c); | Same thing but the fill character is c. |
string PadRight (int n); | Like the first form of PadLeft but filling on the right. |
string PadRight(int n, char c); | Like the second form of PadLeft but filling on the right. |
String Remove(int pos, int nb); | Returns a string which is the one on which the method relates, minus number of characters from the pos-th character:
string s1 = “123456”, s; s = s1.Remove (1, 2); s contains “1456” while s1 is unchanged. |
String Replace(string oldString, string newString); | Returns a string which is the one on which the method relates but in which each old string substring has been replaced by the new string substring:
string s, s1 = “Hello”; s = s1.Replace (“Xyz”); s contains “Xyz” while s1 is unchanged. |
String Replace (char oldchar, char newChar); | Returns a string on which the method relates but in which each oldchar has been replaced by newChar:
string s, s1 = “Hello”; s = s1.Replace (“Fawad khan”); s contains “Fawad khan” while s1 is unchanged. |
string[] Split (char []); | Returns an array of strings from the string to which the operation is performed. A array of string separators is passed as an argument (here a single separator: space) :
string s = “Hello dear friend”; string [] ts = s.Split (new char [] {‘‘}); ts [0] contains “Hello”, ts [1] “dear” and ts [2] “friend”. |
Bool StartsWith(string s); | Returns true if the string to be operated on begins with string s.
string s = “Hello”; bool b = s.StartsWith (“Good”); b is false. |
String Substring (int pos, int nb); | Return a string by extracting nb characters starting from the position:
string s, s1 = “Hello”; s = s1.Substring (1, 2); s contains one. |
string ToLower (); | Returns the string after converting characters to lowercase. |
string ToUpper(); | Returns the string after converting characters to uppercase. The method returns a string object but does not modify the string object on which the method relates.
string s, s1 = “abc”, s2 = “student”; s = s1.ToUpper(); s = s2.ToUpper(); s contains “ABC” first and then “Student”. |
string Trim(); | Removes leading and trailing white space in the string. Trim returns the string modified but does not modify the string on which the method relates.
string s = ” Good day “; s = s.Trim(); s now contains the string “Good day”. |
string TrimEnd(char[]); | Removes the characters passed in arguments from the end of the string. The chain is swiped from right to left and the operation ends as soon as an unspecified character in argument is found. In the first example, we remove, several times if necessary, a single character while in the second we remove several characters:
string s = “ABC1 2”, s1, s2; s1 = s.TrimEnd (new char [] {‘‘}); s2 = s.TrimEnd (new char [] {‘‘, ‘1’, ‘2’}); s1 contains ABC1 2 and s2 ABC. |
string TrimStart (char []); | Same thing but the characters are removed at the beginning of the string. |
C# String Programming Examples:
Program Example: how to use C# String class method Concat in programming:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s1 = "Fawad", s2 = " Khan", s; s = String.Concat(s1, s2); Console.WriteLine(s); Console.ReadKey(); } } |
Output:
1 |
Fawad khan |
Program Example: how to use c# String class method contains in programming:
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 50 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string ani = "calf, cow, pig"; if (ani.Contains("cow")) { Console.WriteLine("Contain"); } else { Console.WriteLine("not Contain"); } Console.ReadKey(); } } |
Output:
1 |
Contain |
Program Example: how to use C# string class method Copy in programming:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s1 = "Programmingdigest", s2; s2 = String.Copy(s1); Console.WriteLine(s2); Console.ReadKey(); } } |
Output:
1 |
Programmingdigest |
Program Example : how to use C# String class method Insert in programming:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s = "Progr", s2 = "amming digest",s3; s3= s.Insert(5, s2); Console.WriteLine(s3); Console.ReadKey(); } } |
Output:
1 |
Programming digest |
Program Example: how to use C# string class method PadLeft in programming:
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 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s = "Programming", s1="digest",s3,s4; s3 = s.PadLeft(15); s4 = s1.PadLeft(20); Console.WriteLine(s3 + s4); Console.ReadKey(); } } |
Output:
Program Example: how to use C# string class method ToUpper() in programming;
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 50 51 52 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s1 = "programming", s2 = " digest", s3,s4; s3 = s1.ToUpper(); s4 = s2.ToUpper(); Console.WriteLine(s3+s4); Console.ReadKey(); } } |
Output:
1 |
PROGRAMMING DIGEST |
Program Example: how to use c# string class method ToLower() in programming
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 50 51 52 |
using System; using System.Collections.Generic; using System.IO; public class Demo { static void Main() { string s1 = "PROGRAMMIGN", s2 = " DIGEST", s3,s4; s3 = s1.ToLower(); s4 = s2.ToLower(); Console.WriteLine(s3+s4); Console.ReadKey(); } } |
Output:
1 |
programming digest |