Monday, February 20, 2012

Return First Array Item that has duplicates!

Code:
  //in your main function  
   #region testdata  
  //string[] split_cities = new string[] { "perth", "sydney", "perth" };  
  //string[] split_cities = new string[] { "perth", "sydney", "gold" };  
  //string[] split_cities = new string[] { "nsw", "sydney", "sydney" };  
  //string[] split_cities = new string[] { "nsw", "nsw", "sydney" };  
  //string[] split_cities = new string[] { "nsw", "coast", "sydney", "nsw" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "nsw" };  
  string[] split_cities = new string[] { "auck", "nsw", "nsw", "coasts" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "auck" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "auc" };  
  #endregion  
        #region string method  
        string occur = OccurMoreThanOnceString(split_cities);  
        if (!occur.Equals(string.Empty))  
        {  
          Console.Write(occur);  
        }  
        else  
        {  
          Console.Write("No duplicates");  
        }  
        #endregion  
  //method declaration  
  //------------------------------------------------------------  
   private static string OccurMoreThanOnceString(string[] split_cities)  
      {  
        string occur_more = "";  
        int check_index = 0;  
        string temp = split_cities[0].ToLower().Trim();  
        for (int j = 0; j < split_cities.Length; j++)  
        {  
          if (check_index == j) //array to be checked is same location   
          {  
            continue;  
          }  
          else  
          {  
            string x = split_cities[j].ToLower().Trim();  
            if (temp.Equals(split_cities[j].ToLower().Trim()))  
            {  
              occur_more = temp;  
              break;  
            }  
          }  
          //if it has reached end of loop  
          if (j == split_cities.Length - 1)  
          {  
            ++check_index;  
            temp = split_cities[check_index];  
            j = -1; //reset loop  
          }  
        }  
        return occur_more;  
      } 

0 comments:

Post a Comment