Basic string operations in C#

By Feb 12, 2017

Description:

We present here, in a very detailed way, the basic operations on character strings in C# and give many examples.

Preferencesoft

In this article, we explain the basic operations on strings in C#.

Introduction

Strings in C#, are represented by a class, are by default encoded in UTF16 and are immutable.
As we cannot directly change the content of a string, we use methods (functions) to operate on strings, that create a new string from the old one.

Creating a string

To create a literal string, just declare it as follows:

string str = "ABCDEF0123456789";
string st = @"ABCDEF
0123456789";

@ is used to declare a verbatim literal string.

We may use the constructor of the class string:

string str = new string(new char[] {'0', '5', 'A'});
string strC = new string('C', 10); // CCCCCCCCCC

We can also get a string by converting from a StringBuilder object:

StringBuilder sb = new StringBuilder("ABCD");
string str = sb.ToString();

A string can also be obtained from an array of characters:

char[] ca = { 'A', 'B', 'C' };
string st = string.Join(null, ca);

Get a character in a string

A string consists of elements of class char and can be indexed, with the first character having index 0.
To get the character at index i in a string, just use the brackets or ElementAt

 string str = "R2V2";
  Console.WriteLine(str.ElementAt(0)); 
  Console.WriteLine(str[0]);

To obtain the last character of the string str, it is possible to use Length which gives the length of a string:

string str = "KodFor";
  Console.WriteLine(str[str.Length-1]);

Output:

    r

More simply, the method Last returns the last character of a string:

string str = "KodFor";
Console.WriteLine(str.Last());

Output:

    r

Set a character in a string

In fact, it is impossible to replace the character at index i in a string with another character.

One method is to split the string at the place of the character and concatenate it with the new character. But it is better to work with a StringBuilder and then convert it to a string.

string str = "KodFor";
StringBuilder sb = new StringBuilder(str);
sb[0] = 'C';
Console.WriteLine(sb.ToString());

Output:

    CodFor

Pro tip: If you work with fixed-length strings and if you need to change several characters in different positions, you will earn to perform these operations on a char array and convert it to a string at the end.

Example:

string str = "KODFOR";
   char[] ca = str.ToCharArray();
   int len = str.Length;
   for (int i = 0; i < len; i++)
       ca[i] = (char)((ca[i] - 65 + 1) % 26 + 65); // 65 is the code of the character A
   Console.WriteLine(string.Join(null,ca));

Output:

      LPEGPS

Concatenation

To concatenate two or more strings, simply place the operator + between the strings. The Concat method of the string class can also be used to concatenate strings. The operator += appends the string at the right of the operator to the other string.

string str1 = "KOD";
string str2 = "FOR";
Console.WriteLine(str1 + str2);
Console.WriteLine(string.Concat(str1,str2));
str1 += str2;
Console.WriteLine(str1);

Output:

    KODFOR
    KODFOR
    KODFOR

It is possible to concatenate a string and a char:

string str = " KODFOR ";
Console.WriteLine('=' + str + '=');

Output:

    = KODFOR =

We can also use StringBuilder and the Append method to concatenate the strings:

StringBuilder sb = new StringBuilder(50);
Random r = new Random();
for (int i = 0; i < 20; i++)
{
    sb.Append(r.NextDouble().ToString());
    sb.Append(",");
}
Console.WriteLine(sb.ToString());

Output:

0.137871366058416, 0.524812362401193, 0.12529619556167, 0.0675763273926342, 0.669907675436655, 0.551772995177551, 0.292626850908914, 0.0811208286700402, 0.733243596615849, 0.895995679728685, 0.670415791529424, 0.361521834675931, 0.909407119690165, 0.298777635348392, 0.882236334440408, 0.452982637310858, 0.122445397136009, 0.952326535225067, 0.98607885604076, 0.173734942532021,

Pro tip: This way should be preferred in case we need to perform many concatenations.

We can also use the Format method to concatenate strings:

string str = "KODFOR";
Console.WriteLine(string.Format("{0}{1}",str,"+"));

Output:

    KODFOR+

String comparison

To determine whether two strings are equal or different, we use the operators == and !=
Although a variable of string type is a reference, the comparison is performed in depth character by character and not on the references.

string str1 = "KODFOR";
string str2 = "Programming";
if (str1 == str2)
{
    Console.WriteLine("=");
}
else
{
    Console.WriteLine(str1);
}
Console.WriteLine(string.Compare(str1, str2));

Output:

    KODFOR
    -1

To determine whether a string is empty, it is best to use the IsNullOrEmpty method to predict the case where the string would have not been initialized.

Example:

string str1 = null;
string str2 = "";
Console.WriteLine(string.IsNullOrEmpty(str1));
Console.WriteLine(string.IsNullOrEmpty(str2));
Console.WriteLine(str1 == "");
Console.WriteLine(str2 == "");

Output:

    True
    True
    False
    True

The Compare method determines the sort order of two strings and return -1, 0 or 1.

string aa = "AA";
string ab = "AB";
Console.WriteLine(string.Compare(aa,ab));
Console.WriteLine(string.Compare(aa, aa));
Console.WriteLine(string.Compare(ab, aa));

Output:

    -1
    0
    1

Substring Extraction

The SubString method of the string class can be used to extract a substring of a string.

To extract a substring of a given length at a certain position:

string str = "The art of computer programming";
Console.WriteLine(str.Substring(11,8));

Output:

    computer

To extract a substring of a given length from the start:

string str = "The art of computer programming";
Console.WriteLine(str.Substring(0, 7));
Console.WriteLine(str.Remove(7));

Output:

    The art
    The art

To extract a substring from a given position to the end:

string str = "The art of computer programming";
Console.WriteLine(str.Substring(11));

Output:

    computer programming

We can also extract substring using a regular expression:

string str = "The art of computer programming";
Regex re = new Regex(@"[ap]\w\w", RegexOptions.Compiled);
foreach (Match itemMatch in re.Matches(str))
{
    Console.WriteLine(itemMatch);
}

Output:

    art
    put
    pro
    amm

We get all the words with 3 letters starting with a or p.

Substring Removal

To delete a specified number of characters beginning at a given position in a string, we use the Remove method of the string class.

To remove a substring of a string matching a certain pattern, we use the Replace method of the Regex class.

string str = "If you are born poor it's not your mistake, But if you die poor it's your mistake";
 
// Removes all chars after index 42
Console.WriteLine(str.Remove(42));
 
// Removes 43 characters after index 19
Console.WriteLine(str.Remove(19, 43));

Output:

    If you are born poor it's not your mistake
    If you are born poor it's your mistake

Now, use a regular expression to remove certain substrings:

string str = @"We were five hundred, but with swift support 
Grew to three thousand as we reached the port...
The Cid, Corneille";
 
 
Regex re = new Regex(@"(tho\w+|\nT.*)", RegexOptions.Compiled);
Console.WriteLine(re.Replace(str, string.Empty));

Output:

    We were five hundred, but with swift support
    Grew to three  as we reached the port...

Substring Replacement

To replace substring of a string by a given string, we use the Replace method of the string class.

To replace a substring of a string matching a certain pattern by a given string, we use the Replace method of the Regex class.

string str = @"Look I am surfing the Web";
 
Console.WriteLine(str);
Console.WriteLine(str.Replace("Web", "biggest wave in the world"));

Output:

    Look I am surfing the Web
    Look I am surfing the biggest wave in the world

Replace wave

Now, use a regular expression to replace certain substrings:

string str = @"__/a/____/b/____/c/____/d/____/e/__";
Regex re = new Regex(@"/\w/", RegexOptions.Compiled);
Console.WriteLine(re.Replace(str, "/x/"));

Output:

    __/x/____/x/____/x/____/x/____/x/__

 

It is possible to retrieve the matched string:

string str = @"__/a/____/b/____/c/____/d/____/e/__";

Regex re = new Regex(@"/(\w)/", RegexOptions.Compiled);
Console.WriteLine(re.Replace(str, "|$1|"));

Output

    __|a|____|b|____|c|____|d|____|e|__

Splitting strings

We can split a string into several substrings in the place where is found a given character.
To split a string, we use the Split method of the class String. In return, we get a string array made up strings appearing between the separators.

Example:

string str = "cat,dog,bird,cow,sheep,chicken";
 
string[] sa = str.Split(',');
foreach (string s in sa)
{
    Console.WriteLine(s);
}

Output

    cat
    dog
    bird
    cow
    sheep
    chicken

We can also split with several separators:

string str = @"A/B|C\D/E|F";
 
string[] sa = str.Split(new char[] { '/', '\\', '|'});
foreach (string s in sa)
{
    Console.WriteLine(s);
}

Output

    A
    B
    C
    D
    E
    F

It is also possible to use strings matching a regular expression pattern as a separator.

string str = @"Text 1. ABC 12. DEF 23. GHI 34. KLM";
Regex reg = new Regex(@"\d+\. *", RegexOptions.Compiled);
string[] sa = reg.Split(str);
foreach (string s in sa)
{
    Console.WriteLine(s);
}

Output

    Text
    ABC
    DEF
    GHI
    KLM

Sometimes it is important to keep the separators. To do this simply surround the regular expression.

string str = @"ABCD/EFGHI?JKLMNO:PQRSTUV";
Regex reg = new Regex(@"([/?:])", RegexOptions.Compiled);
string[] sa = reg.Split(str);
foreach (string s in sa)
{
    Console.WriteLine(s);
}

Output

    ABCD
    /
    EFGHI
    ?
    JKLMNO
    :
    PQRSTUV

We can also paste the separators in the end of string, or at the beginning by using these regular expressions:

(?<=[/?:]) (?<= positive lookbehind) or (?=[/?:]) (?= positive lookahead)


CSharp

Categories

Share

Follow


KodFor Privacy Policy