C sharp string functions

C sharp string functions DEFAULT

Strings (C# Programming Guide)

A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). The Length property of a string represents the number of objects it contains, not the number of Unicode characters. To access the individual Unicode code points in a string, use the StringInfo object.

string vs. System.String

In C#, the keyword is an alias for String. Therefore, and are equivalent, regardless it is recommended to use the provided alias as it works even without . The class provides many methods for safely creating, manipulating, and comparing strings. In addition, the C# language overloads some operators to simplify common string operations. For more information about the keyword, see string. For more information about the type and its methods, see String.

Declaring and Initializing Strings

You can declare and initialize strings in various ways, as shown in the following example:

Note that you do not use the new operator to create a string object except when initializing the string with an array of chars.

Initialize a string with the Empty constant value to create a new String object whose string is of zero length. The string literal representation of a zero-length string is "". By initializing strings with the Empty value instead of null, you can reduce the chances of a NullReferenceException occurring. Use the static IsNullOrEmpty(String) method to verify the value of a string before you try to access it.

Immutability of String Objects

String objects are immutable: they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of and are concatenated to form a single string, the two original strings are unmodified. The operator creates a new string that contains the combined contents. That new object is assigned to the variable , and the original object that was assigned to is released for garbage collection because no other variable holds a reference to it.

Because a string "modification" is actually a new string creation, you must use caution when you create references to strings. If you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified. The following code illustrates this behavior:

For more information about how to create new strings that are based on modifications such as search and replace operations on the original string, see How to modify string contents.

Regular and Verbatim String Literals

Use regular string literals when you must embed escape characters provided by C#, as shown in the following example:

Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

String Escape Sequences

Escape sequenceCharacter nameUnicode encoding
\'Single quote0x0027
\"Double quote0x0022
\\Backslash0x005C
\0Null0x0000
\aAlert0x0007
\bBackspace0x0008
\fForm feed0x000C
\nNew line0x000A
\rCarriage return0x000D
\tHorizontal tab0x0009
\vVertical tab0x000B
\uUnicode escape sequence (UTF-16) (range: 0000 - FFFF; example: = "ç")
\UUnicode escape sequence (UTF-32) (range: 000000 - 10FFFF; example: = "👽")
\xUnicode escape sequence similar to "\u" except with variable length (range: 0 - FFFF; example: or or = "ç")

Warning

When using the escape sequence and specifying less than 4 hex digits, if the characters that immediately follow the escape sequence are valid hex digits (i.e. 0-9, A-F, and a-f), they will be interpreted as being part of the escape sequence. For example, produces "¡", which is code point U+00A1. However, if the next character is "A" or "a", then the escape sequence will instead be interpreted as being and produce "ਚ", which is code point U+0A1A. In such cases, specifying all 4 hex digits (e.g. ) will prevent any possible misinterpretation.

Note

At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string will appear in the watch window as "C:\\files.txt".

Format Strings

A format string is a string whose contents are determined dynamically at runtime. Format strings are created by embedding interpolated expressions or placeholders inside of braces within a string. Everything inside the braces () will be resolved to a value and output as a formatted string at runtime. There are two methods to create format strings: string interpolation and composite formatting.

String Interpolation

Available in C# 6.0 and later, interpolated strings are identified by the special character and include interpolated expressions in braces. If you are new to string interpolation, see the String interpolation - C# interactive tutorial for a quick overview.

Use string interpolation to improve the readability and maintainability of your code. String interpolation achieves the same results as the method, but improves ease of use and inline clarity.

Beginning with C# 10, you can use string interpolation to initialize a constant string when all the expressions used for placeholders are also constant strings.

Composite Formatting

The String.Format utilizes placeholders in braces to create a format string. This example results in similar output to the string interpolation method used above.

For more information on formatting .NET types see Formatting Types in .NET.

Substrings

A substring is any sequence of characters that is contained in a string. Use the Substring method to create a new string from a part of the original string. You can search for one or more occurrences of a substring by using the IndexOf method. Use the Replace method to replace all occurrences of a specified substring with a new string. Like the Substring method, Replace actually returns a new string and does not modify the original string. For more information, see How to search strings and How to modify string contents.

Accessing Individual Characters

You can use array notation with an index value to acquire read-only access to individual characters, as in the following example:

If the String methods do not provide the functionality that you must have to modify individual characters in a string, you can use a StringBuilder object to modify the individual chars "in-place", and then create a new string to store the results by using the StringBuilder methods. In the following example, assume that you must modify the original string in a particular way and then store the results for future use:

Null Strings and Empty Strings

An empty string is an instance of a System.String object that contains zero characters. Empty strings are used often in various programming scenarios to represent a blank text field. You can call methods on empty strings because they are valid System.String objects. Empty strings are initialized as follows:

By contrast, a null string does not refer to an instance of a System.String object and any attempt to call a method on a null string causes a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings. The following examples illustrate some cases in which a reference to a null string does and does not cause an exception to be thrown:

Using StringBuilder for Fast String Creation

String operations in .NET are highly optimized and in most cases do not significantly impact performance. However, in some scenarios such as tight loops that are executing many hundreds or thousands of times, string operations can affect performance. The StringBuilder class creates a string buffer that offers better performance if your program performs many string manipulations. The StringBuilder string also enables you to reassign individual characters, something the built-in string data type does not support. This code, for example, changes the content of a string without creating a new string:

In this example, a StringBuilder object is used to create a string from a set of numeric types:

Strings, Extension Methods and LINQ

Because the String type implements IEnumerable<T>, you can use the extension methods defined in the Enumerable class on strings. To avoid visual clutter, these methods are excluded from IntelliSense for the String type, but they are available nevertheless. You can also use LINQ query expressions on strings. For more information, see LINQ and Strings.

Related Topics

Sours: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/

C# Strings

❮ PreviousNext ❯


C# Strings

Strings are used for storing text.

A variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type and assign it a value:

Run example »


String Length

A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the property:

Example

Run example »


Other Methods

There are many string methods available, for example and , which returns a copy of the string converted to uppercase or lowercase:

Example

Run example »


String Concatenation

The operator can be used between strings to combine them. This is called concatenation:

Example

Run example »

Note that we have added a space after "John" to create a space between firstName and lastName on print.

You can also use the method to concatenate two strings:

Example

Run example »



String Interpolation

Another option of string concatenation, is string interpolation, which substitutes values of variables into placeholders in a string. Note that you do not have to worry about spaces, like with concatenation:

Example

Run example »

Also note that you have to use the dollar sign () when using the string interpolation method.

String interpolation was introduced in C# version 6.


Access Strings

You can access the characters in a string by referring to its index number inside square brackets .

This example prints the first character in myString:

Example

Run example »

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character (1) in myString:

Example

Run example »

You can also find the index position of a specific character in a string, by using the method:

Example

Run example »

Another useful method is , which extracts the characters from a string, starting from the specified character position/index, and returns a new string. This method is often used together with to get the specific character position:

Example

Run example »


Special Characters

Because strings must be written within quotes, C# will misunderstand this string, and generate an error:

The solution to avoid this problem, is to use the backslash escape character.

The backslash () escape character turns special characters into string characters:

Escape characterResultDescription
\''Single quote
\""Double quote
\\\Backslash

The sequence   inserts a double quote in a string:

Example

Try it Yourself »

The sequence   inserts a single quote in a string:

The sequence   inserts a single backslash in a string:

Other useful escape characters in C# are:


Adding Numbers and Strings

WARNING!

C# uses the + operator for both addition and concatenation.

Remember: Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example

Run example »

If you add two strings, the result will be a string concatenation:

Example

Run example »


C# Exercises


❮ PreviousNext ❯


Sours: https://www.w3schools.com/cs/cs_strings.php
  1. Undercut haircut girl
  2. Traditional office chairs leather
  3. Massimo and laura
  4. Masscan for termux
  5. Porsha williams wedding dress

String Class

Definition

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Represents text as a sequence of UTF-16 code units.

Inheritance
Attributes

SerializableAttributeComVisibleAttribute

Implements

IEnumerable<Char>IEnumerableIComparableIComparable<String>IConvertibleIEquatable<String>ICloneable

A string is a sequential collection of characters that's used to represent text. A String object is a sequential collection of System.Char objects that represent a string; a System.Char object corresponds to a UTF-16 code unit. The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). For more information about the immutability of strings, see the Immutability and the StringBuilder class section. The maximum size of a String object in memory is 2-GB, or about 1 billion characters.

For more information about Unicode, UTF-16, code units, code points, and the Char and Rune types, see Introduction to character encoding in .NET.

In this section:

Instantiate a String object
Char objects and Unicode characters
Strings and The Unicode Standard
Strings and embedded null characters
Strings and indexes
Null strings and empty strings
Immutability and the StringBuilder class
Ordinal vs. culture-sensitive operations
Normalization
String operations by category

Instantiate a String object

You can instantiate a String object in the following ways:

  • By assigning a string literal to a String variable. This is the most commonly used method for creating a string. The following example uses assignment to create several strings. Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.

  • By calling a String class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about String constructors, see the String constructor summary.

  • By using the string concatenation operator (+ in C# and & or + in Visual Basic) to create a single string from any combination of String instances and string literals. The following example illustrates the use of the string concatenation operator.

  • By retrieving a property or calling a method that returns a string. The following example uses the methods of the String class to extract a substring from a larger string.

  • By calling a formatting method to convert a value or object to its string representation. The following example uses the composite formatting feature to embed the string representation of two objects into a string.

Char objects and Unicode characters

Each character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded by using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

Note

Note that, because a String instance consists of a sequential collection of UTF-16 code units, it is possible to create a String object that is not a well-formed Unicode string. For example, it is possible to create a string that has a low surrogate without a corresponding high surrogate. Although some methods, such as the methods of encoding and decoding objects in the System.Text namespace, may performs checks to ensure that strings are well-formed, String class members don't ensure that a string is well-formed.

A single Char object usually represents a single code point; that is, the numeric value of the Char equals the code point. For example, the code point for the character "a" is U+0061. However, a code point might require more than one encoded element (more than one Char object). The Unicode standard defines two types of characters that correspond to multiple Char objects: graphemes, and Unicode supplementary code points that correspond to characters in the Unicode supplementary planes.

  • A grapheme is represented by a base character followed by one or more combining characters. For example, the character ä is represented by a Char object whose code point is U+0061 followed by a Char object whose code point is U+0308. This character can also be defined by a single Char object that has a code point of U+00E4. As the following example shows, a culture-sensitive comparison for equality indicates that these two representations are equal, although an ordinary ordinal comparison does not. However, if the two strings are normalized, an ordinal comparison also indicates that they are equal. (For more information on normalizing strings, see the Normalization section.)

  • A Unicode supplementary code point (a surrogate pair) is represented by a Char object whose code point is a high surrogate followed by a Char object whose code point is a low surrogate. The code units of high surrogates range from U+D800 to U+DBFF. The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. The following example creates a surrogate character and passes it to the Char.IsSurrogatePair(Char, Char) method to determine whether it is a surrogate pair.

Strings and the Unicode Standard

Characters in a string are represented by UTF-16 encoded code units, which correspond to Char values.

Each character in a string has an associated Unicode character category, which is represented in .NET by the UnicodeCategory enumeration. The category of a character or a surrogate pair can be determined by calling the CharUnicodeInfo.GetUnicodeCategory method.

.NET maintains its own table of characters and their corresponding categories, which ensures that a specific version of a .NET implementation running on different platforms returns identical character category information. On all .NET versions and across all OS platforms, character category information is provided by the Unicode Character Database.

The following table lists .NET versions and the versions of the Unicode Standard on which their character categories are based.

.NET versionVersion of the Unicode Standard
.NET Framework 1.1The Unicode Standard, Version 4.0.0
.NET Framework 2.0The Unicode Standard, Version 5.0.0
.NET Framework 3.5The Unicode Standard, Version 5.0.0
.NET Framework 4The Unicode Standard, Version 5.0.0
.NET Framework 4.5The Unicode Standard, Version 6.3.0
.NET Framework 4.5.1The Unicode Standard, Version 6.3.0
.NET Framework 4.5.2The Unicode Standard, Version 6.3.0
.NET Framework 4.6The Unicode Standard, Version 6.3.0
.NET Framework 4.6.1The Unicode Standard, Version 6.3.0
.NET Framework 4.6.2 and later versionsThe Unicode Standard, Version 8.0.0
.NET Core 2.1The Unicode Standard, Version 8.0.0
.NET Core 3.1The Unicode Standard, Version 11.0.0
.NET 5The Unicode Standard, Version 13.0.0

In addition, .NET supports string comparison and sorting based on the Unicode standard. .NET Framework 4 and previous versions maintain their own table of string data. This is also true of versions of .NET Framework starting with .NET Framework 4.5 running on Windows 7. Starting with .NET Framework 4.5 running on Windows 8 and later versions of the Windows operating system, the runtime delegates string comparison and sorting operations to the operating system. On .NET Core and .NET 5+, string comparison and sorting information is provided by International Components for Unicode libraries (except on Windows versions prior to Windows 10 May 2019 Update). The following table lists the versions of .NET and the versions of the Unicode Standard on which character comparison and sorting are based.

Strings and embedded null characters

In .NET, a String object can include embedded null characters, which count as a part of the string's length. However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to String objects:

  • The value returned by the or functions does not necessarily equal String.Length.

  • The string created by the or functions is not necessarily identical to the string created by the String.Copy method.

You should ensure that native C and C++ code that instantiates String objects, and code that is passed String objects through platform invoke, don't assume that an embedded null character marks the end of the string.

Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. They are considered only for ordinal or case-insensitive ordinal comparisons. On the other hand, embedded null characters are always considered when searching a string with methods such as Contains, StartsWith, and IndexOf.

Strings and indexes

An index is the position of a Char object (not a Unicode character) in a String. An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as IndexOf and LastIndexOf, return the index of a character or substring in the string instance.

The Chars[] property lets you access individual Char objects by their index position in the string. Because the Chars[] property is the default property (in Visual Basic) or the indexer (in C#), you can access the individual Char objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains.

Because the String class implements the IEnumerable interface, you can also iterate through the Char objects in a string by using a construct, as the following example shows.

Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one Char object. In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. To work with Unicode characters instead of Char objects, use the System.Globalization.StringInfo and TextElementEnumerator classes, or the String.EnumerateRunes method and the Rune struct. The following example illustrates the difference between code that works with Char objects and code that works with Unicode characters. It compares the number of characters or text elements in each word of a sentence. The string includes two sequences of a base character followed by a combining character.

This example works with text elements by using the StringInfo.GetTextElementEnumerator method and the TextElementEnumerator class to enumerate all the text elements in a string. You can also retrieve an array that contains the starting index of each text element by calling the StringInfo.ParseCombiningCharacters method.

For more information about working with units of text rather than individual Char values, see Introduction to character encoding in .NET.

Null strings and empty strings

A string that has been declared but has not been assigned a value is . Attempting to call methods on that string throws a NullReferenceException. A null string is different from an empty string, which is a string whose value is "" or String.Empty. In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the Int32.Parse method throws an ArgumentNullException, and passing an empty string throws a FormatException. In other cases, a method argument can be either a null string or an empty string. For example, if you are providing an IFormattable implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier.

The String class includes the following two convenience methods that enable you to test whether a string is or empty:

  • IsNullOrEmpty, which indicates whether a string is either or is equal to String.Empty. This method eliminates the need to use code such as the following:

  • IsNullOrWhiteSpace, which indicates whether a string is , equals String.Empty, or consists exclusively of white-space characters. This method eliminates the need to use code such as the following:

The following example uses the IsNullOrEmpty method in the IFormattable.ToString implementation of a custom class. The method supports the "G", "C", "F", and "K" format strings. If an empty format string or a format string whose value is is passed to the method, its value is changed to the "G" format string.

Immutability and the StringBuilder class

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

Because strings are immutable, string manipulation routines that perform repeated additions or deletions to what appears to be a single string can exact a significant performance penalty. For example, the following code uses a random number generator to create a string with 1000 characters in the range 0x0001 to 0x052F. Although the code appears to use string concatenation to append a new character to the existing string named , it actually creates a new String object for each concatenation operation.

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string. The following example replaces the String used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a StringBuilder object.

Ordinal vs. culture-sensitive operations

Members of the String class perform either ordinal or culture-sensitive (linguistic) operations on a String object. An ordinal operation acts on the numeric value of each Char object. A culture-sensitive operation acts on the value of the String object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. The two kinds of operations can produce very different results when they are performed on the same string.

.NET also supports culture-insensitive linguistic string operations by using the invariant culture (CultureInfo.InvariantCulture), which is loosely based on the culture settings of the English language independent of region. Unlike other System.Globalization.CultureInfo settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures.

Important

If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters.

Important

Most methods that perform string operations include an overload that has a parameter of type StringComparison, which enables you to specify whether the method performs an ordinal or culture-sensitive operation. In general, you should call this overload to make the intent of your method call clear. For best practices and guidance for using ordinal and culture-sensitive operations on strings, see Best Practices for Using Strings.

Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. The following sections discuss each category of operation.

You can download the sorting weight tables, a set of text files that contain information on the character weights used in sorting and comparison operations, from the following links:

Casing

Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. Often, a casing operation is performed before a string comparison. For example, a string might be converted to uppercase so that it can be compared with another uppercase string. You can convert the characters in a string to lowercase by calling the ToLower or ToLowerInvariant method, and you can convert them to uppercase by calling the ToUpper or ToUpperInvariant method. In addition, you can use the TextInfo.ToTitleCase method to convert a string to title case.

Note

.NET Core running on Linux and macOS systems only: The collation behavior for the C and Posix cultures is always case-sensitive because these cultures do not use the expected Unicode collation order. We recommend that you use a culture other than C or Posix for performing culture-sensitive, case-insensitive sorting operations.

Casing operations can be based on the rules of the current culture, a specified culture, or the invariant culture. Because case mappings can vary depending on the culture used, the result of casing operations can vary based on culture. The actual differences in casing are of three kinds:

  • Differences in the case mapping of LATIN CAPITAL LETTER I (U+0049), LATIN SMALL LETTER I (U+0069), LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130), and LATIN SMALL LETTER DOTLESS I (U+0131). In the tr-TR (Turkish (Turkey)) and az-Latn-AZ (Azerbaijan, Latin) cultures, and in the tr, az, and az-Latn neutral cultures, the lowercase equivalent of LATIN CAPITAL LETTER I is LATIN SMALL LETTER DOTLESS I, and the uppercase equivalent of LATIN SMALL LETTER I is LATIN CAPITAL LETTER I WITH DOT ABOVE. In all other cultures, including the invariant culture, LATIN SMALL LETTER I and LATIN CAPITAL LETTER I are lowercase and uppercase equivalents.

    The following example demonstrates how a string comparison designed to prevent file system access can fail if it relies on a culture-sensitive casing comparison. (The casing conventions of the invariant culture should have been used.)

  • Differences in case mappings between the invariant culture and all other cultures. In these cases, using the casing rules of the invariant culture to change a character to uppercase or lowercase returns the same character. For all other cultures, it returns a different character. Some of the affected characters are listed in the following table.

    CharacterIf changed toReturns
    MICRON SIGN (U+00B5)UppercaseGREEK CAPITAL LETTER MU (U+-39C)
    LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130)LowercaseLATIN SMALL LETTER I (U+0069)
    LATIN SMALL LETTER DOTLESS I (U+0131)UppercaseLATIN CAPITAL LETTER I (U+0049)
    LATIN SMALL LETTER LONG S (U+017F)UppercaseLATIN CAPITAL LETTER S (U+0053)
    LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON (U+01C5)LowercaseLATIN SMALL LETTER DZ WITH CARON (U+01C6)
    COMBINING GREEK YPOGEGRAMMENI (U+0345)UppercaseGREEK CAPITAL LETTER IOTA (U+0399)
  • Differences in case mappings of two-letter mixed-case pairs in the ASCII character range. In most cultures, a two-letter mixed-case pair is equal to the equivalent two-letter uppercase or lowercase pair. This is not true for the following two-letter pairs in the following cultures, because in each case they are compared to a digraph:

    • "lJ" and "nJ" in the hr-HR (Croatian (Croatia)) culture.

    • "cH" in the cs-CZ (Czech (Czech Republic)) and sk-SK (Slovak (Slovakia)) cultures.

    • "aA" in the da-DK (Danish (Denmark)) culture.

    • "cS", "dZ", "dZS", "nY", "sZ", "tY", and "zS" in the hu-HU (Hungarian (Hungary)) culture.

    • "cH" and "lL" in the es-ES_tradnl (Spanish (Spain, Traditional Sort)) culture.

    • "cH", "gI", "kH", "nG" "nH", "pH", "qU', "tH", and "tR" in the vi-VN (Vietnamese (Vietnam)) culture.

    However, it is unusual to encounter a situation in which a culture-sensitive comparison of these pairs creates problems, because these pairs are uncommon in fixed strings or identifiers.

The following example illustrates some of the differences in casing rules between cultures when converting strings to uppercase.

Parsing and formatting

Formatting and parsing are inverse operations. Formatting rules determine how to convert a value, such as a date and time or a number, to its string representation, whereas parsing rules determine how to convert a string representation to a value such as a date and time. Both formatting and parsing rules are dependent on cultural conventions. The following example illustrates the ambiguity that can arise when interpreting a culture-specific date string. Without knowing the conventions of the culture that was used to produce a date string, it is not possible to know whether 03/01/2011, 3/1/2011, and 01/03/2011 represent January 3, 2011 or March 1, 2011.

Similarly, as the following example shows, a single string can produce different dates depending on the culture whose conventions are used in the parsing operation.

String comparison and sorting

Conventions for comparing and sorting strings vary from culture to culture. For example, the sort order may be based on phonetics or on the visual representation of characters. In East Asian languages, characters are sorted by the stroke and radical of ideographs. Sorting also depends on the order languages and cultures use for the alphabet. For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. In addition, comparisons can be case-sensitive or case-insensitive, and casing rules might differ by culture. Ordinal comparison, on the other hand, uses the Unicode code points of individual characters in a string when comparing and sorting strings.

Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the String.Compare(String, String, StringComparison) method compares two strings based on the StringComparison parameter. If the parameter value is StringComparison.CurrentCulture, the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is StringComparison.Ordinal, the method performs an ordinal comparison. Consequently, as the following example shows, if the current culture is U.S. English, the first call to the String.Compare(String, String, StringComparison) method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A".

.NET supports word, string, and ordinal sort rules:

  • A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. For a list of the String methods that compare two strings using word sort rules, see the String operations by category section.

  • A string sort also performs a culture-sensitive comparison. It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. Two strings can be compared using string sort rules by calling the CompareInfo.Compare method overloads that have an parameter that is supplied a value of CompareOptions.StringSort. Note that this is the only method that .NET provides to compare two strings using string sort rules.

  • An ordinal sort compares strings based on the numeric value of each Char object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the String methods that compare two strings using ordinal sort rules, see the String operations by category section.

A culture-sensitive comparison is any comparison that explicitly or implicitly uses a CultureInfo object, including the invariant culture that is specified by the CultureInfo.InvariantCulture property. The implicit culture is the current culture, which is specified by the Thread.CurrentCulture and CultureInfo.CurrentCulture properties. There is considerable variation in the sort order of alphabetic characters (that is, characters for which the Char.IsLetter property returns ) across cultures. You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a CultureInfo object to a string comparison method such as Compare(String, String, CultureInfo, CompareOptions). You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, or any member of the CompareOptions enumeration other than CompareOptions.Ordinal or CompareOptions.OrdinalIgnoreCase to an appropriate overload of the Compare method. A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not.

The following example illustrates the difference between culture-sensitive and ordinal comparison. The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the Compare method is called). Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "AEble".

Use the following general guidelines to choose an appropriate sorting or string comparison method:

  • If you want the strings to be ordered based on the user's culture, you should order them based on the conventions of the current culture. If the user's culture changes, the order of sorted strings will also change accordingly. For example, a thesaurus application should always sort words based on the user's culture.

  • If you want the strings to be ordered based on the conventions of a specific culture, you should order them by supplying a CultureInfo object that represents that culture to a comparison method. For example, in an application designed to teach students a particular language, you want strings to be ordered based on the conventions of one of the cultures that speaks that language.

  • If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes.

  • For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the Equals method.

Note

The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET. On .NET Core, string comparison depends on the version of the Unicode Standard supported by the underlying operating system. In .NET Framework 4.5 and later versions running on Windows 8 or later, sorting, casing, normalization, and Unicode character information conform to the Unicode 6.0 standard. On other Windows operating systems, they conform to the Unicode 5.0 standard.

For more information about word, string, and ordinal sort rules, see the System.Globalization.CompareOptions topic. For additional recommendations on when to use each rule, see Best Practices for Using Strings.

Ordinarily, you don't call string comparison methods such as Compare directly to determine the sort order of strings. Instead, comparison methods are called by sorting methods such as Array.Sort or List<T>.Sort. The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. Note that each type of sort produces a unique ordering of strings in its array.

Tip

Internally, .NET uses sort keys to support culturally sensitive string comparison. Each character in a string is given several categories of sort weights, including alphabetic, case, and diacritic. A sort key, represented by the SortKey class, provides a repository of these weights for a particular string. If your app performs a large number of searching or sorting operations on the same set of strings, you can improve its performance by generating and storing sort keys for all the strings that it uses. When a sort or comparison operation is required, you use the sort keys instead of the strings. For more information, see the SortKey class.

If you don't specify a string comparison convention, sorting methods such as Array.Sort(Array) perform a culture-sensitive, case-sensitive sort on strings. The following example illustrates how changing the current culture affects the order of sorted strings in an array. It creates an array of three strings. First, it sets the property to en-US and calls the Array.Sort(Array) method. The resulting sort order is based on sorting conventions for the English (United States) culture. Next, the example sets the property to da-DK and calls the Array.Sort method again. Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark).

Warning

If your primary purpose in comparing strings is to determine whether they are equal, you should call the String.Equals method. Typically, you should use Equals to perform an ordinal comparison. The String.Compare method is intended primarily to sort strings.

String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the IndexOf method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to Empty and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case.

Search in strings

String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string.

The search methods in the String class that search for an individual character, such as the IndexOf method, or one of a set of characters, such as the IndexOfAny method, all perform an ordinal search. To perform a culture-sensitive search for a character, you must call a CompareInfo method such as CompareInfo.IndexOf(String, Char) or CompareInfo.LastIndexOf(String, Char). Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. The following example illustrates the difference between the String.IndexOf(Char) and CompareInfo.IndexOf(String, Char) methods when searching for an individual character. The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison.

On the other hand, String class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type StringComparison. The sole exception is Contains, which performs an ordinal search.

Testing for equality

Use the String.Compare method to determine the relationship of two strings in the sort order. Typically, this is a culture-sensitive operation. In contrast, call the String.Equals method to test for equality. Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation.

The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". As a result, file system access is inadvertently permitted. On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied.

Normalization

Some Unicode characters have multiple representations. For example, any of the following code points can represent the letter "ắ":

  • U+1EAF

  • U+0103 U+0301

  • U+0061 U+0306 U+0301

Multiple representations for a single character complicate searching, sorting, matching, and other string operations.

The Unicode standard defines a process called normalization that returns one binary representation of a Unicode character for any of its equivalent binary representations. Normalization can use several algorithms, called normalization forms, that follow different rules. .NET supports Unicode normalization forms C, D, KC, and KD. When strings have been normalized to the same normalization form, they can be compared by using ordinal comparison.

An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding Char objects in each string. The String class includes a number of methods that can perform an ordinal comparison, including the following:

You can determine whether a string is normalized to normalization form C by calling the String.IsNormalized() method, or you can call the String.IsNormalized(NormalizationForm) method to determine whether a string is normalized to a specified normalization form. You can also call the String.Normalize() method to convert a string to normalization form C, or you can call the String.Normalize(NormalizationForm) method to convert a string to a specified normalization form. For step-by-step information about normalizing and comparing strings, see the Normalize() and Normalize(NormalizationForm) methods.

The following simple example illustrates string normalization. It defines the letter "ố" in three different ways in three different strings, and uses an ordinal comparison for equality to determine that each string differs from the other two strings. It then converts each string to the supported normalization forms, and again performs an ordinal comparison of each string in a specified normalization form. In each case, the second test for equality shows that the strings are equal.

For more information about normalization and normalization forms, see System.Text.NormalizationForm, as well as Unicode Standard Annex #15: Unicode Normalization Forms and the Normalization FAQ on the unicode.org website.

String operations by category

The String class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string.

Compare strings

You can compare strings to determine their relative position in the sort order by using the following String methods:

  • Compare returns an integer that indicates the relationship of one string to a second string in the sort order.

  • CompareOrdinal returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points.

  • CompareTo returns an integer that indicates the relationship of the current string instance to a second string in the sort order. The CompareTo(String) method provides the IComparable and IComparable<T> implementations for the String class.

Test strings for equality

You call the Equals method to determine whether two strings are equal. The instance Equals(String, String, StringComparison) and the static Equals(String, StringComparison) overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal.

Find characters in a string

The String class includes two kinds of search methods:

Warning

If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. For more information, see .NET Regular Expressions.

Modify a string

The String class includes the following methods that appear to modify the value of a string:

  • Insert inserts a string into the current String instance.

  • PadLeft inserts one or more occurrences of a specified character at the beginning of a string.

  • PadRight inserts one or more occurrences of a specified character at the end of a string.

  • Remove deletes a substring from the current String instance.

  • Replace replaces a substring with another substring in the current String instance.

  • ToLower and ToLowerInvariant convert all the characters in a string to lowercase.

  • ToUpper and ToUpperInvariant convert all the characters in a string to uppercase.

  • Trim removes all occurrences of a character from the beginning and end of a string.

  • TrimEnd removes all occurrences of a character from the end of a string.

  • TrimStart removes all occurrences of a character from the beginning of a string.

Important

All string modification methods return a new String object. They don't modify the value of the current instance.

The String.Split method separates a single string into multiple strings. Overloads of the method allow you to specify multiple delimiters, to limit the number of substrings that the method extracts, to trim white space from substrings, and to specify whether empty strings (which occur when delimiters are adjacent) are included among the returned strings.

Combine strings

The following String methods can be used for string concatenation:

  • Concat combines one or more substrings into a single string.

  • Join concatenates one or more substrings into a single element and adds a separator between each substring.

Format values

The String.Format method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. The Format method is often used to do the following:

  • To embed the string representation of a numeric value in a string.

  • To embed the string representation of a date and time value in a string.

  • To embed the string representation of an enumeration value in a string.

  • To embed the string representation of some object that supports the IFormattable interface in a string.

  • To right-justify or left-justify a substring in a field within a larger string.

For detailed information about formatting operations and examples, see the Format overload summary.

Copy a string

You can call the following String methods to make a copy of a string:

  • Clone returns a reference to an existing String object.

  • Copy creates a copy of an existing string.

  • CopyTo copies a portion of a string to a character array.

Normalize a string

In Unicode, a single character can have multiple code points. Normalization converts these equivalent characters into the same binary representation. The String.Normalize method performs the normalization, and the String.IsNormalized method determines whether a string is normalized.

For more information and an example, see the Normalization section earlier in this topic.

Constructors

String(Char*)

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

String(Char*, Int32, Int32)

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

String(Char, Int32)

Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

String(Char[])

Initializes a new instance of the String class to the Unicode characters indicated in the specified character array.

String(Char[], Int32, Int32)

Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

String(ReadOnlySpan<Char>)

Initializes a new instance of the String class to the Unicode characters indicated in the specified read-only span.

String(SByte*)

Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

String(SByte*, Int32, Int32)

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

String(SByte*, Int32, Int32, Encoding)

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

Fields

Empty

Represents the empty string. This field is read-only.

Properties

Methods

Sours: https://docs.microsoft.com/en-us/dotnet/api/system.string

C# - Strings



In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.

Creating a String Object

You can create string object using one of the following methods −

  • By assigning a string literal to a String variable

  • By using a String class constructor

  • By using the string concatenation operator (+)

  • By retrieving a property or calling a method that returns a string

  • By calling a formatting method to convert a value or an object to its string representation

The following example demonstrates this −

using System; namespace StringApplication { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = "Rowan"; lname = "Atkinson"; char []letters= { 'H', 'e', 'l', 'l','o' }; string [] sarray={ "Hello", "From", "Tutorials", "Point" }; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //by using string constructor { 'H', 'e', 'l', 'l','o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //methods returning string { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); } } }

When the above code is compiled and executed, it produces the following result −

Full Name: RowanAtkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

Properties of the String Class

The String class has the following two properties −

Sr.No.Property & Description
1

Chars

Gets the Char object at a specified position in the current String object.

2

Length

Gets the number of characters in the current String object.

Methods of the String Class

The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods −

Sr.No.Methods & Description
1

public static int Compare(string strA, string strB)

Compares two specified string objects and returns an integer that indicates their relative position in the sort order.

2

public static int Compare(string strA, string strB, bool ignoreCase )

Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.

3

public static string Concat(string str0, string str1)

Concatenates two string objects.

4

public static string Concat(string str0, string str1, string str2)

Concatenates three string objects.

5

public static string Concat(string str0, string str1, string str2, string str3)

Concatenates four string objects.

6

public bool Contains(string value)

Returns a value indicating whether the specified String object occurs within this string.

7

public static string Copy(string str)

Creates a new String object with the same value as the specified string.

8

public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)

Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters.

9

public bool EndsWith(string value)

Determines whether the end of the string object matches the specified string.

10

public bool Equals(string value)

Determines whether the current String object and the specified String object have the same value.

11

public static bool Equals(string a, string b)

Determines whether two specified String objects have the same value.

12

public static string Format(string format, Object arg0)

Replaces one or more format items in a specified string with the string representation of a specified object.

13

public int IndexOf(char value)

Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.

14

public int IndexOf(string value)

Returns the zero-based index of the first occurrence of the specified string in this instance.

15

public int IndexOf(char value, int startIndex)

Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position.

16

public int IndexOf(string value, int startIndex)

Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position.

17

public int IndexOfAny(char[] anyOf)

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

18

public int IndexOfAny(char[] anyOf, int startIndex)

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position.

19

public string Insert(int startIndex, string value)

Returns a new string in which a specified string is inserted at a specified index position in the current string object.

20

public static bool IsNullOrEmpty(string value)

Indicates whether the specified string is null or an Empty string.

21

public static string Join(string separator, params string[] value)

Concatenates all the elements of a string array, using the specified separator between each element.

22

public static string Join(string separator, string[] value, int startIndex, int count)

Concatenates the specified elements of a string array, using the specified separator between each element.

23

public int LastIndexOf(char value)

Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.

24

public int LastIndexOf(string value)

Returns the zero-based index position of the last occurrence of a specified string within the current string object.

25

public string Remove(int startIndex)

Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.

26

public string Remove(int startIndex, int count)

Removes the specified number of characters in the current string beginning at a specified position and returns the string.

27

public string Replace(char oldChar, char newChar)

Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.

28

public string Replace(string oldValue, string newValue)

Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.

29

public string[] Split(params char[] separator)

Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.

30

public string[] Split(char[] separator, int count)

Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.

31

public bool StartsWith(string value)

Determines whether the beginning of this string instance matches the specified string.

32

public char[] ToCharArray()

Returns a Unicode character array with all the characters in the current string object.

33

public char[] ToCharArray(int startIndex, int length)

Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.

34

public string ToLower()

Returns a copy of this string converted to lowercase.

35

public string ToUpper()

Returns a copy of this string converted to uppercase.

36

public string Trim()

Removes all leading and trailing white-space characters from the current String object.

You can visit MSDN library for the complete list of methods and String class constructors.

Examples

The following example demonstrates some of the methods mentioned above −

Comparing Strings

using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey() ; } } }

When the above code is compiled and executed, it produces the following result −

This is test and This is text are not equal.

String Contains String

using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "This is test"; if (str.Contains("test")) { Console.WriteLine("The sequence 'test' was found."); } Console.ReadKey() ; } } }

When the above code is compiled and executed, it produces the following result −

The sequence 'test' was found.

Getting a Substring

using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.Substring(23); Console.WriteLine(substr); } } }

When the above code is compiled and executed, it produces the following result −

San Pedro

Joining Strings

using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string[] starray = new string[]{"Down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"}; string str = String.Join("\n", starray); Console.WriteLine(str); } } }

When the above code is compiled and executed, it produces the following result −

Down the way nights are dark And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop
Sours: https://www.tutorialspoint.com/csharp/csharp_strings.htm

String functions sharp c

C# String Functions

C# String Functions

Introduction to C# String Function

Strings are the most essential part of C# programming language, and also is one of the important data types in modern languages including C#. The string data type is defined in the .NET base class library and it is a collection of characters in which each character is a Unicode character. The keyword string is an object of System. String type, which is used to denote a sequential collection of characters that is called a text and the string.  The keywords consist of two types called string and String to declare string variables. Both string and String are comparably equal, so you can make use of whichever the naming convention you like better to define string variables. To avoid NullReferenceException, by initializing strings with the Empty value in case of null.

Examples of String Functions in C#

Predefined string functions are available in C# programming, Let’s see how to use string function in C# programming with the help of examples

Clone returns an instance of String. In other words, it returns another copy of that data. The return value will be merely another view of similar data. The Clone() method does not take any parameters.

Example:

Output:

String              : StringFunctions

Clone String    : StringFunctions

CompareTo() method is used to compare the string instance with a particular String object. It checks whether the String occurrence appears in the same position as the particular string or not. Once comparing to strings it returns an integer value as output.

Example:

Output:

0

1

Contains() method is used to return a value signifying whether the particular substring presents within this string or not. If the particular substring is found in this string, it returns true otherwise false. The return value of this method is either true or false a Boolean value.

Example:

Output:

True

False

EndsWith() method is used to verify whether the particular string matches the end of this string or not. If the particular string is present at the end of this string, then the result will be true otherwise false. The return value of this method is either true or false a Boolean value.

Example:

Output:

True

False

Equals() method is used to compare whether two particular String objects have an identical value or not. If both strings have similar value, it returns true otherwise false. The return value of the Equals() method is either true or false a Boolean value.

Example:

Output:

True

False

GetHashCode() method is used to getting the hash code of a specified string. It returns an integer value. The return value of GetHashCode() is the hash code of a string object.

Example:

Output:

1085385658

GetType() method is used to obtain the type of current object. It returns the System. Type of current instance which is used for reflection.

Example:

Output:

System.String

IndexOf() is used to get the index of the particular character present in the string. It returns the index position of the first occurrence of a particular character as an integer value.

Example:

Output:

1

This C# string function is used to convert a string into lowercase. It returns a string in lower case. The return value of ToLower () is a string.

Example:

Output:

string functions

ToUpper() method is used to convert the string into uppercase. The return value of ToUpper () is a string.

Example:

Output:

STRING FUNCTIONS

Insert() method is used to insert the particular string at a specified index number. The index number starts from 0. After inserting the particular string, it returns a new modified string. The return value of Insert() is a new modified string.

Example:

Output:

String- Functions

Length is a string property that returns a number of characters in a string and here spaces count as characters.

Example:

Output:

16

This string function in C# is used to replaces the character to get another string in which all occurrences of a particular character in this string are replaced with another specified character.

Example:

Output:

Strings in C#

Split() method is used to split the string based on the specified value of characters in an array. The return value of this method is the string array.

Example:

Output:

Welcome
C
Sharp

SubString() method is used to retrieve a substring from the current occurrence of the String. The parameter “startIndex” will denote the initial position of substring and then substring will continue to the end of the string. The return value type is System. String.

Example:

Output:

C Sharp

StringFu

Func

Conclusion

In this article, we learned the basics of strings in C# and how to use the String functions available in C#. Hope this article would have helped out you in understanding String Methods using C#

Recommended Articles

This has been a guide to C# String Functions. Here we discussed how to use string function in C# programming with the help of examples and output. You can also go through our other suggested articles to learn more –

  1. C# Commands
  2. Uses Of C#
  3. C# Interview Questions and Answers
  4. String Array in C#
Sours: https://www.educba.com/c-sharp-string-functions/
Working With Strings - C# - Tutorial 6

C# Strings

Method NameDescriptionClone()It is used to return a reference to this instance of String.Compare(String, String)It is used to compares two specified String objects. It returns an integer that indicates their relative position in the sort order.CompareOrdinal(String, String)It is used to compare two specified String objects by evaluating the numeric values of the corresponding Char objects in each string..CompareTo(String)It is used to compare this instance with a specified String object. It indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.Concat(String, String)It is used to concatenate two specified instances of String.Contains(String)It is used to return a value indicating whether a specified substring occurs within this string.Copy(String)It is used to create a new instance of String with the same value as a specified String.CopyTo(Int32, Char[], Int32, Int32)It is used to copy a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters. EndsWith(String)It is used to check that the end of this string instance matches the specified string.Equals(String, String)It is used to determine that two specified String objects have the same value.Format(String, Object)It is used to replace one or more format items in a specified string with the string representation of a specified object.GetEnumerator()It is used to retrieve an object that can iterate through the individual characters in this string.GetHashCode()It returns the hash code for this string.GetType()It is used to get the Type of the current instance. GetTypeCode()It is used to return the TypeCode for class String.IndexOf(String)It is used to report the zero-based index of the first occurrence of the specified string in this instance.Insert(Int32, String)It is used to return a new string in which a specified string is inserted at a specified index position.Intern(String)It is used to retrieve the system's reference to the specified String.IsInterned(String)It is used to retrieve a reference to a specified String.IsNormalized()It is used to indicate that this string is in Unicode normalization form C.IsNullOrEmpty(String)It is used to indicate that the specified string is null or an Empty string.IsNullOrWhiteSpace(String)It is used to indicate whether a specified string is null, empty, or consists only of white-space characters.Join(String, String[])It is used to concatenate all the elements of a string array, using the specified separator between each element.LastIndexOf(Char)It is used to report the zero-based index position of the last occurrence of a specified character within String.LastIndexOfAny(Char[])It is used to report the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.Normalize()It is used to return a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C.PadLeft(Int32)It is used to return a new string that right-aligns the characters in this instance by padding them with spaces on the left.PadRight(Int32)It is used to return a new string that left-aligns the characters in this string by padding them with spaces on the right.Remove(Int32)It is used to return a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.Replace(String, String)It is used to return a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.Split(Char[])It is used to split a string into substrings that are based on the characters in an array.StartsWith(String)It is used to check whether the beginning of this string instance matches the specified string.Substring(Int32)It is used to retrieve a substring from this instance. The substring starts at a specified character position and continues to the end of the string.ToCharArray()It is used to copy the characters in this instance to a Unicode character array.ToLower()It is used to convert String into lowercase.ToLowerInvariant()It is used to return convert String into lowercase using the casing rules of the invariant culture.ToString()It is used to return instance of String.ToUpper()It is used to convert String into uppercase.Trim()It is used to remove all leading and trailing white-space characters from the current String object.TrimEnd(Char[])It Is used to remove all trailing occurrences of a set of characters specified in an array from the current String object.TrimStart(Char[])It is used to remove all leading occurrences of a set of characters specified in an array from the current String object.
Sours: https://www.javatpoint.com/c-sharp-strings

Now discussing:

C# String Functions and Properties

logotypeIn this chapter you will learn
  • What is string?
  • How many types of string function in C#?
  • How to use C# string function in programming?
  • What is the difference between string and String?

In C# programming, is another kind of data type that represents Unicode Characters. It is the alias of System.String, however, you can also write System.String instead of a string. It is the sequence of character in which each character is a Unicode character.

There is no difference between string and String because a string is the alias of System.String. Most of the developers get confused what to use between sting and String. Technically there is no difference between them and they can use any of them. However, you will have to use “using System” to use the String in C#. Another difference is String is a class name whereas a string is a reserved keyword. You should always use string instead of String.

C# string function

String FunctionsDefinitions
Make clone of string.
Compare two strings and returns integer value as output. It returns 0 for true and 1 for false.
The C# Contains method checks whether specified character or string is exists or not in the string value.
This EndsWith Method checks whether specified character is the last character of string or not.
The Equals Method in C# compares two string and returns Boolean value as output.
This method returns HashValue of specified string.
It returns the System.Type of current instance.
It returns the Stystem.TypeCode for class System.String.
Returns the index position of first occurrence of specified character.
Converts String into lower case based on rules of the current culture.
Converts String into Upper case based on rules of the current culture.
Insert the string or character in the string at the specified position.
This method checks whether this string is in Unicode normalization form C.
Returns the index position of last occurrence of specified character.
It is a string property that returns length of string.
This method deletes all the characters from beginning to specified index position.
This method replaces the character.
This method splits the string based on specified value.
It checks whether the first character of string is same as specified character.
This method returns substring.
Converts string into char array.
It removes extra whitespaces from beginning and ending of string.

Programming Examples of C# String Function:

using System.Text; namespace string_function { class Program { static void Main(string[] args) { string firstname; string lastname; firstname = "Steven Clark"; lastname = "Clark"; Console.WriteLine(firstname.Clone()); // Make String Clone Console.WriteLine(firstname.CompareTo(lastname)); //Compare two string value and returns 0 for true and 1 for false Console.WriteLine(firstname.Contains("ven")); //Check whether specified value exists or not in string Console.WriteLine(firstname.EndsWith("n")); //Check whether specified value is the last character of string Console.WriteLine(firstname.Equals(lastname)); //Compare two string and returns true and false Console.WriteLine(firstname.GetHashCode()); //Returns HashCode of String Console.WriteLine(firstname.GetType()); //Returns type of string Console.WriteLine(firstname.GetTypeCode()); //Returns type of string Console.WriteLine(firstname.IndexOf("e")); //Returns the first index position of specified value the first index position of specified value Console.WriteLine(firstname.ToLower()); //Covert string into lower case Console.WriteLine(firstname.ToUpper()); //Convert string into Upper case Console.WriteLine(firstname.Insert(0, "Hello")); //Insert substring into string Console.WriteLine(firstname.IsNormalized()); //Check Whether string is in Unicode normalization from C Console.WriteLine(firstname.LastIndexOf("e")); //Returns the last index position of specified value Console.WriteLine(firstname.Length); //Returns the Length of String Console.WriteLine(firstname.Remove(5)); //Deletes all the characters from begining to specified index. Console.WriteLine(firstname.Replace('e','i')); // Replace the character string[] split = firstname.Split(new char[] { 'e' }); //Split the string based on specified value Console.WriteLine(split[0]); Console.WriteLine(split[1]); Console.WriteLine(split[2]); Console.WriteLine(firstname.StartsWith("S")); //Check wheter first character of string is same as specified value Console.WriteLine(firstname.Substring(2,5)); //Returns substring Console.WriteLine(firstname.ToCharArray()); //Converts an string into char array. Console.WriteLine(firstname.Trim()); //It removes starting and ending white spaces from string. } } }

Output

Steven Clark 1 True False False 1470518261 System.String String 2 steven clark STEVEN CLARK HelloSteven Clark True 4 12 Steve Stivin Clark St v n Clark True even Steven Clark Steven Clark _

 


Sours: https://www.completecsharptutorial.com/csharp-articles/csharp-string-function.php


3578 3579 3580 3581 3582