C# String Pattern to display from aabbac to a3b2c1

Introduction

In this article, we mainly focus on logical programs, which are commonly asked in interviews. The main reason for conducting this logical program test is to check your problem-solving skills. Now we see one of the logical programs, which mostly asks the interviewer to write a program to count how many times each letter appears in a given string.

C# Coding:

The below code is used to check any string data, and it is not hardcoded. Users need to enter a string value that needs to check the number of letters that appear.


public static void Main(string[] args)	
{
 Console.Write("Enter String: ");
 string _string = Console.ReadLine();
 if (!string.IsNullOrWhiteSpace(_string))
 {
	char[] _stringArray = _string.ToCharArray();
	for (int i = 0; i < _stringArray.Length; i++)
	{
	 if(_stringArray[i]!='@')
	 {
		int _count = 0;
		Console.Write(_stringArray[i]);
		for (int j = i; j < _stringArray.Length; j++)
		{
		 if (i == j)
			_count = 1;

		 if (i != j "" _stringArray[i] == _stringArray[j])
		 {
			_stringArray[j] = '@';
			_count = _count + 1;
		 }
	    }
	    Console.Write(_count);
	  }
	}
  }
}

Code Explanation:


Console.Write("Enter String: ");
string _string = Console.ReadLine();

The first line of the code asks users to enter a string or type something, and the second line is used to store that entered string data into a string variable, i.e., _string.

Example: Enter String: aabbac

 
if (!string.IsNullOrWhiteSpace(_string))
{
 ---
 ---
}

The above If condition checks whether the string variable contains any data or not, if the condition is true that means string variable contains data then it will enter into the if block.

char[] _stringArray = _string.ToCharArray();

The above char[] array code converts a string to a char array and how its char[] array looks like I shown below

aabbac
Index012345

The total length of the char[] array is 6 - { _stringArray.Length; }

 
for (int i = 0; i < _stringArray.Length; i++)
{
 if(_stringArray[i]!='@')
 {
  ---
  ---
 }
}

The for loop is used to iterate each char of the char[] object, and after iteration, an if condition is used to check if the char[] array object contains any '@' char or not. If '@' char contains, then it skips the current iteration and moves to the next iteration.

To check the first character with another character in the same char[] array object, we need to use another for loop, i.e., a nested for loop, which we are going to define in the 'if' condition.

In the nested for loop, we defined an int variable, i.e., _count, whose default value is 'Zero', and this count will increase whenever the first char value is equal to another char in the same char[] array condition is true. At the same time, another char value will be changed to '@'.

.Net Fiddle With Running Example

You can check the current code is working or not from here

Post a Comment

0 Comments