0

我只是一个初学者,我不知道如何开始这项任务。我有一些想法,虽然我试图用谷歌搜索这个问题,但它们似乎都太复杂了,我无法成功。任何帮助,将不胜感激。顺便说一句,我正在用 C 语言编程。

4

2 回答 2

3

以下是一组可以帮助您自己解决问题的任务。

  1. 尝试在 c 中打开/关闭文件。搜索“如何在 C 中打开文件”
  2. 尝试从 c 中的文件中读取。搜索“如何在 C 中读取文本文件”
  3. 现在您知道如何打开和读取文件了。尝试打开文件,并逐字打印文件中的内容。提示,您需要循环,并可能标记化。
  4. 尝试确定一个单词的长度(c 中的一个字符串)。搜索“计算 c 中的字符串长度”(您可以使用一个标准函数)
  5. 当您阅读每个单词时(从第 3 步开始),打印出它旁边的长度。搜索“如何打印格式化输出 c”
  6. 现在你有了文件中的每个单词和它的长度。您需要做的就是获取第一个单词的长度,而不是打印出所有其他长度相同的单词,只需计数即可。最后,打印出来。
于 2012-12-11T09:26:25.603 回答
0

有很简单的方法可以做到这一点。就这个:

string text = File.ReadAllText(@"C:\Users\TestFolder\FromThisFileWeRead.txt");
\\you should be carefull, because if file is not exists, you will have an exeption
\\try to catch it your own way

            if (!string.IsNullOrEmpty(text))
            {
                string[] words = text.Split(new char[] {',', ' ', '\t', '\n', '\r'});
                \\separators depend on your text file

                int firstWordLength = words[0].Length;
                int countWordsTheSameLength = 0;

                foreach (string word in words)
                {
                    if(word.Length == firstWordLength)
                    {
                        countWordsTheSameLength++;
                    }
                }

另一种方式与之前类似:

string text = File.ReadAllText(@"C:\Users\TestFolder\FromThisFileWeRead.txt");

            if (!string.IsNullOrEmpty(text))
            {
                int firstWordLength = words[0].Length;
                string[] words = text.Split(new char[] {',', ' ', '\t', '\n', '\r'});
                List<string> wordsList = new List<string>(words);
                int firstWordLength = words[0].Length;
                countWordsTheSameLength = wordsList.FindAll(word => word.Length == firstWordLength).Count;
}

对于这两种情况,您都需要使用System.IO.

我认为这很容易理解。将来您应该尝试 FileStream、StreamRead 和 StreamWrite 类。

祝你好运!

于 2012-12-11T09:36:22.073 回答