Introduction
This article will demonstrate to you the top 10C# string technical interview questions and their answers. This is specific to the C# string, and it is useful for beginners and experienced. As a .NET developer, if you are working with C# programming language, then most of the time, you have faced some challenges while dealing with strings. We have seen most of the interviewers also ask string-related difficult difficult questions like reversing a string, finding duplicate characters in a string, and so on. So, today, we will see the top 10 technical problems related to string and how to resolve that problems. So, let's start the practical demonstration of the technical problems and their solutions.
Problem 1. Find duplicate characters in a string
Solution. In this sample code, we have a string, and we need to find all duplicate characters in the string. Let create twoStringBuilderobjects as aresultandduplicateChar. We will simply loop through string chars and keep track if a char exists or not.
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Find the duplicate characters
public StringBuilder GetDuplicateCharacters(string input)
{
StringBuilder result = new StringBuilder();
HashSet<char> seenChars = new HashSet<char>();
foreach (char item in input)
{
if (!seenChars.Contains(char.ToLower(item)))
{
seenChars.Add(char.ToLower(item));
}
else if (result.ToString().IndexOf(char.ToLower(item)) == -1)
{
result.Append(item);
}
}
return result;
}
}
}
Let's run the program. First, create an object of theStringDataStructureclass and call theGetDuplicateCharactermethod. This method accepts one argument as a string.
StringDataStructure _stringDT = new StringDataStructure();
// Find the duplicate characters in the string
var duplicates = _stringDT.GetDuplicateCharacters("google");
WriteLine("Duplicate characters in 'google' are: " + duplicates);
Output. Here, you can see we have passed "google" as a string, and we got a result as "og". It means these two characters (og)are duplicates in the word "google".
![duplicate cahrachteroutput]()
Problem 2. Get all unique characters in a string
Solution. This is just the opposite of problem 1. In problem 1, we are trying to find duplicate characters, but here, we are trying to find all unique characters. This means just remove duplicate characters, and you will get a unique characters list. If you compare the above and below code, we are now returning the result objectwhere all unique characters are available.
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Find the unique characters
public StringBuilder GetUniqueCharacters(string input)
{
StringBuilder result = new StringBuilder();
HashSet<char> seenChars = new HashSet<char>();
foreach (char item in input)
{
if (!seenChars.Contains(char.ToLower(item)))
{
seenChars.Add(char.ToLower(item));
result.Append(item);
}
}
return result;
}
}
}
Let's run the program and pass a string as "google" in a method GetUniqueCharFromStringas an argument.
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Remove duplicate characters and return the unique characters
public StringBuilder GetUniqueCharFromString(string input)
{
StringBuilder result = new StringBuilder();
HashSet<char> seenChars = new HashSet<char>();
foreach (char item in input)
{
if (!seenChars.Contains(char.ToLower(item)))
{
seenChars.Add(char.ToLower(item));
result.Append(item);
}
}
return result;
}
}
}
Output.Here, you can see the output as"gole". This means after removing duplicate characters from the word "google," we get the "gole" which are unique chars.
![uniquecharactersoutput]()
Problem 3.Reverse a string
Solution. Here, we have to reverse a string. For example, if we pass a string as "hello," then the output should be "olleh". For reversing the string, first, we will check the string should not be null or empty. After that, we will loop on the string from the secondlast index (length- 1)and the output will be added into another string object, "result".
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Reverse the given string
public string ReverseString(string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;
StringBuilder result = new StringBuilder();
for (int i = input.Length - 1; i >= 0; i--)
{
result.Append(input[i]);
}
return result.ToString();
}
}
}
Let's run the program and pass an argument string as "google" into the method "ReverseString".
StringDataStructure _stringDT = new StringDataStructure();
// Reverse the single string
var reversedValue = _stringDT.ReverseString("google");
WriteLine("Reversed string for 'google' is = " + reversedValue);
Output.The output will be as follows.
![0utputfunction]()
Problem 4. Reverse each word of the sentence (string)
Solution.Here, we have not only reversed a string but need to reverse a sentence. Here, we will first split the sentence into a string array and then reverse each word one by one as follows.
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Reverse each word of the sentence
public string ReverseEachString(string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;
string[] words = input.Split(' ');
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.Length; i++)
{
result.Append(ReverseString(words[i]));
if (i != words.Length - 1)
{
result.Append(" ");
}
}
return result.ToString();
}
// Reverses a single string
private string ReverseString(string str)
{
StringBuilder reversed = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
{
reversed.Append(str[i]);
}
return reversed.ToString();
}
}
}
Let's run the program and pass the argument as a string"My name ismukesh"into the methodReverseEachString.
StringDataStructure _stringDT = new StringDataStructure();
// Reverse the string with multiple words
var reversedValue = _stringDT.ReverseEachString("My name is mukesh");
WriteLine("Reversed string for 'My name is mukesh' is = " + reversedValue);
Output.The output will similar to as follows.
![reversevalue]()
Problem 5. Get the word count in a sentence (string)
Solution. Here, we have to count the number of words in a sentence or a string and skip spaces. First, check if the string is not null or empty then we have tosplit thesentence based on spaceand count the length using the Length property.
using System;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Get the count of words in a sentence
public int GetWordCount(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
input = input.Trim();
var length = input.Split(' ').Length;
return length;
}
}
}
Let's run the project and call theGetWordCountmethod to pass an argument as"My name ismukesh".
StringDataStructure _stringDT = new StringDataStructure();
// Get the word count for the string
var wordCountValue = _stringDT.GetWordCount("My name is mukesh");
WriteLine("Word count for the string 'My name is mukesh' is = " + wordCountValue);
Output. The output will be as follows.
![Getwordcountmethod]()
Problem 6. Check if a string is a palindrome or not
Solution. Here we have to check that a string is palindrome or not. Palindrome means when you read it from the beginning or from the last, the characters should be the same. Here, we will check each character from the beginning and compare it from last.
using System;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Check if the string is a palindrome
public bool CheckPalindrome(string input)
{
if (string.IsNullOrEmpty(input))
return false;
input = input.ToLower().Trim();
int min = 0;
int max = input.Length - 1;
while (max >= min)
{
if (input[min] == input[max])
{
min++;
max--;
}
else
{
return false;
}
}
return true;
}
}
}
Let's run the program and call theCheckPalindromemethod to pass"radar" as an argument.
StringDataStructure _stringDT = new StringDataStructure();
// Check if the string is palindrome
bool isPalindromeValue = _stringDT.CheckPalindrome("radar");
WriteLine("Is 'radar' palindrome? = " + isPalindromeValue);
Output. Here is the output, which says "radar" is a palindrome.
![output]()
Problem 7. Check max occurrence character in the string
Solution. Here, we have one string and need to find that character whose occurrence is maximum. First, we will convert that string to a character array and then, using the loop, add it to the dictionary array using a key-value pair. At last, we will check whose has the maximum occurrence using the foreach loop.
using System;
using System.Collections.Generic;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Check the character with the maximum occurrence in the string
public char? CheckMaxOccurrenceOfChar(string input)
{
if (string.IsNullOrEmpty(input))
return null;
input = input.ToLower().Trim();
char[] arr = input.ToCharArray();
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in arr)
{
if (c != ' ')
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount.Add(c, 1);
}
}
}
char? maxOccurrenceChar = null;
int maxOccurrenceValue = 0;
foreach (KeyValuePair<char, int> item in charCount)
{
if (item.Value > maxOccurrenceValue)
{
maxOccurrenceChar = item.Key;
maxOccurrenceValue = item.Value;
}
}
return maxOccurrenceChar;
}
}
}
Let's run the program and call the CheckMaxOccurenceOfChar method and pass"Hello World"as an argument.
StringDataStructure _stringDT = new StringDataStructure();
// Check multiple occurrences of a character in the string
char? multipleOccurrenceChar = _stringDT.CheckMaxOccurrenceOfChar("Hello World");
WriteLine("Multiple occurrence char in 'Hello World' is = " + multipleOccurrenceChar);
Output. Here is the output, and you can see a max occurrence of a character is "l".
![maxoccurenceoutput]()
Problem 8. Get all possible substrings in a string.
Solution. Here, we have one string, and we have to find out all possible substrings in a string. Here, we will use two loops, one inside another one, to create substrings. Based on the loop index value and the Substring method, we will create all possible substrings for the provided string.
using System;
using System.Collections.Generic;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Get the possible substrings of a string
public void GetPossibleSubstring(string word)
{
if (!string.IsNullOrEmpty(word))
{
for (int i = 1; i < word.Length; i++)
{
for (int j = 0; j <= word.Length - i; j++)
{
Console.WriteLine(word.Substring(j, i));
}
}
Console.ReadLine();
}
}
}
}
Let's run the program and call theGetPossibleSubstringmethod to pass "india" as an argument.
StringDataStructure _stringDT = new StringDataStructure();
_stringDT.GetPossibleSubstring("india");
Output. Following is the output; here, you can find all the possible substrings for "india" string.
![string output]()
Problem 9. The first char of each word is in capital letters
Solution. Here, you will get one string. It could be a word or sentence as well. We have to find out the first character of each word and capitalize it. After checking the null or empty string,we will split it into a string array based on space. Then loop through the string array and get the first character of each word using the substring method and capitalize it usingToUppermethod.
using System;
using System.Collections.Generic;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Get the first character of each word in a sentence
public void GetFirstCharForEachWord(string sentence)
{
if (!string.IsNullOrEmpty(sentence))
{
string[] arr = sentence.Split(' ');
foreach (string item in arr)
{
Console.Write(item.Substring(0, 1).ToUpper() + " ");
}
Console.ReadKey();
}
}
}
}
Let's run the program and call the GetFirstCharForEachWord method and pass the argument as"I love myindia.".
StringDataStructure _stringDT = new StringDataStructure();
_stringDT.GetFirstCharForEachWord("I love my india.");
Output. Here is the output as the first character of each word with capitalization.
![output]()
Problem 10. Get the index of string using binary search.
Solution. Here, C# provides the binary search mechanism on array, list, etc. We can use the BinarySearch method. In this method, you can pass an array or list and the strings that need to be searched.
using System;
namespace DataStructureDemo.Example
{
public class StringDataStructure
{
// Get the binary search on string
public void BinarySearchOnString()
{
string[] arr = new string[] { "Hi", "Guest", "I", "Mukesh", "Am" };
Array.Sort(arr); // Am, Guest, Hi, I, Mukesh
var index = Array.BinarySearch<string>(arr, "Hi");
Console.WriteLine("The position of 'Hi' in array is " + index);
}
}
}
Let's run the program and call the BinarySearchOnstringmethod. We are not passing any arguments because we are already creating a string array in the method itself.
StringDataStructure _stringDT = new StringDataStructure();
_stringDT.BinarySearchOnString();
Output
![output binary search]()
Conclusion
So, today we have seen how to solve various string-related problems.
I hope this post will help you. Please post your feedback using the comments below that will help me improve myself for the next post. If you have any questions, please ask your queries in the comment section and If you like this post, please share it with your friends. Thanks
You are here; it means you have found it useful. Please feel free to connect with me meon@Facebook,@Twitter,@LinkedIn,@Google+.