2010-04-06 100 views
2

我是C#的初學者,我試圖編寫一個程序,從輸入的字符串中提取單詞,用戶必須輸入單詞的最小長度以過濾單詞輸出...我的代碼看起來不好或直觀,我用兩個數組countStr來存儲單詞,countArr來存儲對應於每個單詞的單詞長度..但問題是我需要使用哈希表而不是這兩個數組,因爲它們的大小取決於用戶輸入的字符串長度,我認爲這對內存不太安全?在Hashtable實現中需要幫助

這裏是我的卑鄙的代碼,再次我試圖用一個哈希表替換這兩個數組,這怎麼可以做到?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Collections; 

namespace ConsoleApplication2 
{ 
class Program 
{ 

    static void Main(string[] args) 
    { 
     int i = 0 ; 
     int j = 0; 
     string myString = ""; 
     int counter = 0; 
     int detCounter = 0;   

     myString = Console.ReadLine(); 
     string[] countStr = new string[myString.Length]; 
     int[] countArr = new int[myString.Length]; 

     Console.Write("Enter minimum word length:"); 
     detCounter = int.Parse(Console.ReadLine()); 

     for (i = 0; i < myString.Length; i++) 
     { 
      if (myString[i] != ' ') 
      { 
       counter++; 
       countStr[j] += myString[i]; 
      } 
      else 
      { 
       countArr[j] = counter; 
       counter = 0; 
       j++; 
      }            
     } 

     if (i == myString.Length) 
     { 
      countArr[j] = counter; 
     } 

     for (i = 0; i < myString.Length ; i++) 
     { 
      if (detCounter <= countArr[i]) 
      { 
       Console.WriteLine(countStr[i]); 
      } 
     } 

    Console.ReadLine();  

    }   
    } 
} 

回答

12

您對第一次嘗試的操作並不算太差,但這可能會好很多。

第一件事:在解析人類輸入的整數時使用TryParse而不是Parse。如果人類使用「HELLO」而不是整數,那麼如果使用Parse,程序將崩潰;只有當你使用解析器知道它是一個整數。

接下來的事情:考慮使用String.Split將字符串拆分爲一個單詞數組,然後處理單詞數組。

接下來的事情:類似你的代碼有很多數組突變難以閱讀和理解。考慮將您的問題描述爲查詢。你想問什麼?我不確定自己完全理解了你的代碼,但是聽起來像你試圖說「用空格分隔這些字詞串,取最小長度,給我所有字符串中超過最小值的單詞長度。」是?

在這種情況下,寫看起來像這樣的代碼:

string sentence = whatever; 
int minimum = whatever; 
var words = sentence.Split(' '); 
var longWords = from word in words 
       where word.Length >= minimum 
       select word; 
foreach(var longWord in longWords) 
    Console.WriteLine(longWord); 

而且你去那裏。注意代碼是如何讀取的。嘗試編寫代碼,以便代碼傳遞代碼的含義,而不是代碼的機制

+1

感謝您提供的信息豐富的答案,但我有一個問題,請問,爲什麼你經常在減速時使用var而不是字符串和字符串[]? – rafael 2010-04-06 20:22:29

+10

@rafael:好問題。完整的答案會很長,但是簡單地說,我的理由是使用var進一步強調了*機制*上代碼的*意義*。什麼是文字?誰在乎?這是一個詞的集合,這就是你需要擔心的算法的目的。什麼是長詞?誰在乎?這是過濾「單詞」的結果,這就是你需要擔心的一切。它是字符串[]還是列表或IEnumerable 或IList 還是別的?不重要的是它的意義,而不是它的存儲細節。 – 2010-04-06 20:26:47

0

一個字。 Dictiary(或HashTable)。兩者都是標準數據類型,您可以使用

0

使用此詞典(在你的情況下,你正在尋找一本詞典)。

您提取的字符串將是關鍵字,它的長度值。

Dictionary<string, int> words = new Dictionary<string,int>(); 
//algorithm 
words.Add(word, length);