我是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();
}
}
}
感谢您提供的信息丰富的答案,但我有一个问题,请问,为什么你经常在减速时使用var而不是字符串和字符串[]? – rafael 2010-04-06 20:22:29
@rafael:好问题。完整的答案会很长,但是简单地说,我的理由是使用var进一步强调了*机制*上代码的*意义*。什么是文字?谁在乎?这是一个词的集合,这就是你需要担心的算法的目的。什么是长词?谁在乎?这是过滤“单词”的结果,这就是你需要担心的一切。它是字符串[]还是列表或IEnumerable 或IList 还是别的?不重要的是它的意义,而不是它的存储细节。 –
2010-04-06 20:26:47