(C# Language) Practice Exercise on String Manipulation

Suppose there is a string s = "aubcd123paqeaw". Write three programs (1) Write a program to count the number of 'a' in this string. (2) Write a program to extract the numeric part into a string variable and display it. (3) Replace all vowels by underscore.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

Write a program to count the number of 'a' in this string

Open the program.cs file of the solution explorer and start by creating the given string.


//-- program 1 --//

string s = "aubcd123paqeaw";

int count = 0;

foreach (Char k in s)
{
  if ('a' == k)
  {
    count++;
  }
}

// prints 3 
Console.WriteLine($"Number of a = {count}");

Create an int count = 0 so that we can use it to store the number of 'a'.

A string is a sequence of Char. So we can set a for-each loop - foreach char k in s. Next, an if condition checks if the char is an 'a'. If so, the counter is incremented. Finally, the contents of the counter are printed!

Video Explanation (see it happen!)

Please watch the following youtube video:

Write a program to extract the numeric part into a string variable and display it

Open the program.cs file of the solution explorer and again start by creating the given string.


//-- program 2 --//

string s = "aubcd123paqeaw";

using System.Text;

StringBuilder sb = new();

foreach(Char k in s)
{
  if(Char.IsDigit(k))
  {
    sb.Append(k);
  }
}

Console.WriteLine(sb.ToString());

We have to store the numeric part in a separate string. So we start with a StringBuilder.

A for-each loop checks each char of the string if it is a numeral. It uses the static Char.IsDigit function for this check. Alternatively, we could have made a check of ASCII values k >= '0' AND k <='9'. If the char is a numeric, then it is appended to the string builder.

Finally, the string builder is converted to a string and displayed.

Replace all vowels by underscore

Open the program.cs file of the solution explorer and again start by creating the given string.


//-- program 3 --//

string s = "aubcd123paqeaw";

StringBuilder sb2 = new();

foreach (char k in s)
{
  switch (k)
  {
    case 'a': case 'A':
    case 'e': case 'E':
    case 'i': case 'I':
    case 'o': case 'O':
    case 'u': case 'U':
      {
        sb2.Append('_');
      }
      break;

    default:
      {
        sb2.Append(k);
      }
      break;
  }
}

Console.WriteLine(sb2.ToString());

We start with a string builder.

A foreach loop is created to loop through the characters of the given string.

A switch statement appends an underscore to the string builder if the char is a vowel. Otherwise the default case appends the character to the string builder.

Finally, the string builder is converted to a string and displayed.


This Blog Post/Article "(C# Language) Practice Exercise on String Manipulation" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.