Search This Blog

July 30, 2008

String operations using C#.Net

/*
Following are the methods in C#.Net on String for some of the interviews
1. Reverse a string
2. Remove duplicate words in a give string
3. Remove duplicate chars
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Interview
{
class StringOperations
{
/*Reverse the string -- Method 1*/
public string ReverseString(string inputString)
{
StringBuilder sbTemp = new StringBuilder("");
/*Check either the string is empty or null*/
if (String.IsNullOrEmpty(inputString))
{
return sbTemp.ToString();
}
/* If it is a valid string take a single charcter from last till start of the
string*/
for (int i = inputString.Length - 1; i >= 0; i--)
{
sbTemp.Append(inputString.Substring(i, 1));
}
return sbTemp.ToString();
}

/*Remove duplicate words in a give string.*/
public string RemoveDuplicateWords(string stringToRemoveDuplicates)
{
if (String.IsNullOrEmpty(stringToRemoveDuplicates))
{
return "";
}
ArrayList alist = new ArrayList();
foreach (string word in stringToRemoveDuplicates.Split(' '))
{
if (!alist.Contains(word))
{
alist.Add(word);
}
}
return string.Join(" ", (string[])alist.ToArray(typeof(string)));
}

/*Remove duplicate chars*/
public string RemoveDuplicateChars(string removeDups)
{
StringBuilder sb = new StringBuilder(string.Empty);
foreach (char c in removeDups.ToCharArray())
{
if (sb.ToString().IndexOf(c) == -1)
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}

No comments: