随机选择单词并从文本文件中写入单词 [英] Randomly pick word and write word from text file

查看:116
本文介绍了随机选择单词并从文本文件中写入单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有2个文本框和文件test.txt它包含一些单词,每个单词都在单行上,我想随机选择一个单词到textbox1,然后到textbox2我写了一些单词(不一定要写一些单词)像textbox1)和通过按钮的单词我将textbox2中的单词保存到test.txt文件中。谢谢你的回答。

解决方案

我们不做你的功课:这是有原因的。它就是为了让你思考你被告知的事情,并试着理解它。它也在那里,以便您的导师可以识别您身体虚弱的区域,并将更多的注意力集中在补救措施上。



亲自尝试,你可能会发现它不是和你想的一样困难!



但是我会给你一些线索:

首先要弄清楚你想怎么读file:因为单词长度不一样,而且文本文件实际上没有这样的行(它们有行终止字符,这不是一回事),这意味着你不能只说读行 14或读取第723行 - 读者不知道线的起始位置。解决这个问题的最简单方法是将整个文件读入单独的行:File.ReadAllLines方法将在这里提供帮助。

随机性很简单:创建Random类的类级实例,并使用Random 。接下来得到一个随机数(它有有用的重载 - 详见MSDN)。

将数据添加到文件中也很简单:File.AppendAllText方法会这样做,前提是你记得在你添加为行分隔符的每个单词后面加一个'\ n'字符。



试一试 - 这并不复杂,不是真的。

Hallo, i have 2 textboxes and file test.txt it contains some words, each word is on single line and I want to randomly pick one word to textbox1, and to textbox2 i write some word (it not nessessary to write same word like in textbox1) and through button i save word in textbox2 to test.txt file. Thank you for answer.

解决方案

We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

But I'll give you a few clues:
Start by working out how you want to read the file: because words aren't all the same length, and text files don't really have lines as such (they have line termination characters, which isn't the same thing) that means that you can't just say "read line 14" or "read line 723" - the reader doesn't know where the lines start. The easiest way round this problem is to read the whole file into separate lines: the File.ReadAllLines method will help here.
Randomness is easy: Create a class level instance of the Random class, and use Random.Next to get a random number (it has useful overloads - see MSDN for details).
Adding data to the file is also pretty easy: the File.AppendAllText method will do it, provided you remember to include a '\n' character after each word you add as the line separator.

Give it a try - this isn't complicated, not really.


这篇关于随机选择单词并从文本文件中写入单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆