我一直在研究一个项目,我需要在单个行上的文本文件中打印一个单词数组,其位置在数组中。我过去曾使用过streamwriters所以我打算再次使用它,但是我似乎无法编写文本文件。以下是代码:
public partial class Form2 : Form
{
string sentence;
String[] words;
int a;
bool wordAppear;
string textbox2;
string path;
public Form2()
{
InitializeComponent();
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
private void btn1_Click(object sender, EventArgs e)
{
sentence = txt1.Text.ToLower();
words = sentence.Split();
a = words.Length;
MessageBox.Show("Number of Words: " + a);
StreamWriter sw = new StreamWriter(path + @"\file1000.txt");
for (int i=0; i < a; i++)
{
sw.WriteLine(words[i] + " " + i+1);
}
}
}
我的部分任务涉及列出单词首次出现的顺序,例如,如果句子是“我有二十个人有二十个锤子”,那么顺序将是1 2 3 4 5 3 6所以如果有人有任何想法如何做到这一点请你建议他们
答案 0 :(得分:2)
这应该有效(假设是ASCII字符串):
var xs = "I have twenty men with twenty hammers".ToLower().Split();
var memo = new Dictionary<string, int>();
for (var i = 0; i < xs.Length; i++)
{
var index = 0;
if(!memo.TryGetValue(xs[i], out index))
memo.Add(xs[i], i + 1);
}
using(var sw = new StreamWriter(SOME_PATH));
foreach(var x in xs)
sw.WriteLine(x + " " + memo[x]);
答案 1 :(得分:0)
我认为您需要使用Close()方法将其包装起来,并且还要稍微处理... WriteLine()函数。希望这会有所帮助。
...
words = sentence.Split( );
a = words.Length;
MessageBox.Show("Number of Words: " + a);
StreamWriter sw = new StreamWriter(path + @"\file1000.txt");
for (int i = 0; i < a; i++)
{
sw.WriteLine(words[i] + " " + (i + 1).ToString());
}
sw.Close();
}