【发布时间】:2010-04-06 19:54:42
【问题描述】:
我是 C# 的初学者,我试图编写一个从输入的字符串中提取单词的程序,用户必须输入单词的最小长度来过滤输出的单词......我的代码没有看起来不错或直观,我使用了两个数组countStr 来存储单词,countArr 存储对应于每个单词的单词长度.. 但问题是我需要使用哈希表而不是这两个数组,因为它们的大小都是根据用户输入的字符串长度,我认为这对内存或其他东西不太安全?
这是我的简陋代码,我再次尝试用一个哈希表替换这两个数组,如何做到这一点?
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();
}
}
}
【问题讨论】: