Basic C# Coding Questions For Technical Interviews
Introduction
Here, we will try a few frequently asked .NET C# programming questions in technical interviews.
We will be coding everything from scratch and not using any built-in library/functions like “substring”, “LINQ” because in the easy questions the other side wants us to show that we know basics.
In case where a bigger logical problem statement is given we generally use in built libs and functions.
1- Reverse a string in C#?
Now as an answer this can have many variations like:
- Don’t use an extra variable
- Or try to use string builder or char array etc
Use your PC or online
First solution using an extra variable and for loop.
using System;
public class Program
{
public static void Main()
{
String str = "ABCD EFGH Z";
Console.WriteLine(str);
string strReversed = "";
//start reading character from end of the string
for(int i = str.Length - 1; i >= 0; i--){
strReversed += str[i];
}
Console.WriteLine(strReversed);
}
}
https://dotnetfiddle.net/Widget/7BT1Ur
Another solution using extra character array, two pointers, swap, and loop.
using System;
public class Program
{
public static void Main()
{
String str = "AAA Z";
Console.WriteLine(str);
char[] charArray = str.ToCharArray();
//Start reading th string from both ends (start and end)
//this loop runs length/2 times
for (int i = 0, j = str.Length - 1; i < j; i++, j--)
{
charArray[i] = str[j];//read from start of the string & add into char array
charArray[j] = str[i];//read from end of the string & add into char array
}
string strReversed = new string(charArray);
Console.WriteLine(strReversed);
}
}
https://dotnetfiddle.net/UqKxDZ
There are more ways to do it, we shall explore them in coming time.
Till then Mirror — Mirror — Code Mirror.