DEV Community

Mushtariy
Mushtariy

Posted on

String methods

Substring - returns substring into substring.

Example

Code

var longString = "This is very long string";
Console.WriteLine(longString.Substring(5));
Enter fullscreen mode Exit fullscreen mode

Result

is very long string
Enter fullscreen mode Exit fullscreen mode

Replace() - replace the specified old character with the specified new character.

Example

Code

var longString = "This is very stringman";
Console.WriteLine(longString.Replace("is", "IS"));
Console.WriteLine(longString.Replace("very", "VERY"));
Console.WriteLine(longString.Replace("iS", "IS", StringComparison.CurrentCultureIgnoreCase));;
Enter fullscreen mode Exit fullscreen mode

Results

ThIS IS very stringman
This is VERY stringman
ThIS IS very stringman
Enter fullscreen mode Exit fullscreen mode

Join() - joins the given string using the specified separator.

Example

Code

string[] words = {"apple", "banana", "cherry"};
string result = string.Join("-", words);
Console.WriteLine(result);

string[] words2 = {"ananas", "ball"};
string result2 = string.Join("*", words2);
Console.WriteLine(result2);
Enter fullscreen mode Exit fullscreen mode

Results

apple-banana-cherry
ananas*ball
Enter fullscreen mode Exit fullscreen mode

Remove() - returns character from a string.

Example

Code

string tekst = "Hello world";
string tekst1 = tekst.Remove(2, 7);
Console.WriteLine(tekst1);
Enter fullscreen mode Exit fullscreen mode

Results

Held
Enter fullscreen mode Exit fullscreen mode

PadLeft - returns string padded with space or with a specified Unicode character.

Example

Code

string tekst = "Hello";
string tekst1 = tekst.PadLeft(10, '0');
Console.WriteLine(tekst1);
Enter fullscreen mode Exit fullscreen mode

Results

00000Hello
Enter fullscreen mode Exit fullscreen mode

PadRight - returns string padded with space or with a specified Unicode character.

Example

Code

string tekst = "Hello";
string tekst1 = tekst.PadLeft(10, '0');
Console.WriteLine(tekst1);
Enter fullscreen mode Exit fullscreen mode

Results

Hello00000
Enter fullscreen mode Exit fullscreen mode

ToCharArray = converts the string to a char array.

Example

Code

string tekst = "Hello";
char[] charArray = tekst.ToCharArray();

foreach(char c in charArray)
{
    Console.WriteLine(c);
}
Enter fullscreen mode Exit fullscreen mode

Results

H
e
l
l
o
Enter fullscreen mode Exit fullscreen mode

LastIndexOf() - returns index the last occurance of specified string.

Example

Code

string tekst2 = "The quick brown fox jumps over the lazy dog!";
int index = tekst2.LastIndexOf("o");
Console.WriteLine(index);
Enter fullscreen mode Exit fullscreen mode

Results

41
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sabrina_abcdna123 profile image
Sabrina

amazing