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:

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.


C# String literals:

String literals are enclosed in double quotation marks.

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:

Program Example: how to use a backslash in c# Escape sequence:

Output:

@ 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

as well as the formatting of strings using indentations and breaks:



program Example: how to @ in C# escape sequence:

Output:

Line breaks:

In principle, string literals cannot span several lines:

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:

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:

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:

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.

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:

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.

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.

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():

Is not case-sensitive if true is passed as the third argument.

Takes a member of the StringComparison enumeration as the third argument:

Compares the string strA starting at position indexA with the string strB starting at position indexB. It will maximum length characters compared.

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:

There is only a single overload of the CompareOrdinal() method to compare substrings can:

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.

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:

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.

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:

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.


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.

There is no separate method for appending to a string; just pass the length of the original string to Insert():

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:

With Replace() you can search the string for a given string and replace it with a have the second string replaced:

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.

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).

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()

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:



Split()

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).

Output:

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:

Join()

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.


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.

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).

The total length indicates how many characters the result string should have (original number Characters in the original string plus filler characters).

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.

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.

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:

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.

Copy:

In C#, the easiest way to copy strings is to use the assignment operator or the Clone() method:

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():

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.

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:

Output:

Program Example: how to use c# String class method contains in programming:

Output:



Program Example: how to use C# string class method Copy in programming:

Output:

Program Example :  how to use C# String  class method Insert in programming:

Output:

Program Example: how to use C# string class method PadLeft in programming:

Output:

C# Strings


Program Example: how to use C# string class method ToUpper() in programming;

Output:

Program Example: how to use c# string class method ToLower() in programming

Output:

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: