分别读取文本文件中的每个单词

时间:2018-01-27 07:02:06

标签: c# visual-studio

我有文本文件(words.text)包含每行包含字符和等效字的行:

A = 1
B = 2
C = 3
D = 4

我使用以下代码来阅读文本文件

     System.IO.StreamReader file =   
    new System.IO.StreamReader(@"c:\words.txt");  
    while((line = file.ReadLine()) != null)  
    {  
       System.Console.WriteLine (line);  
       counter++;  
    } 

我需要通过计数器更改每个字符(数字)的值并再次保存它,就像这样

A = 3
B = 4
C = 1
D = 2

我想过让每个单词和=成为"第一个"和数字是"秒",并循环第二个

First = "A = ", Second = "1"

我不知道如何让程序读取每一行并确定第一行和第二行

2 个答案:

答案 0 :(得分:2)

您可以简单地将每个行值除以<script type="text/javascript" src="assets/js/core/libraries/jquery.min.js"></script> 字符,以获得第一个和第二个值:

=

答案 1 :(得分:1)

这个怎么样......

// Getting content of the file.
string contents = File.ReadAllText(@"C:\test.txt");

// Separating content           
string[] contentArr  = contents.Split('\n');            

List<string> characterList = new List<string>();
List<int> valueList = new List<int>();

foreach (string value in contentArr)
{
    characterList.Add(string.Join("", value.ToCharArray().Where(Char.IsLetter)).Trim());
    valueList.Add(Int32.Parse(string.Join("", value.ToCharArray().Where(Char.IsDigit))));
}

所有字符都将作为字符串存储在characterList中,并且所有值将作为整数(int)存储在valueList中。

如果您需要阅读或更改值,可以使用forloop(或foreach)这样做。

for (int i = 0; i < contentArr.Length; i++)
{
    //valueList[i] = 5
    Console.WriteLine(characterList[i] + " = " + valueList[i]);
}

//// characters 
//foreach(string value in characterList)
//{
//  Console.WriteLine(value);
//}

//// Values
//foreach(int value in valueList)
//{
//  Console.WriteLine(value);
//}

或者,您可以单独更改值...

valueList[0] = 3;
valueList[1] = 4;
valueList[2] = 1;
valueList[3] = 2;

进行更改后,您可以回写该文件。

string output = "";

for (int i = 0; i < contentArr.Length; i++)
{
    output += characterList[i] + " = " + valueList[i] + Environment.NewLine;
}

File.WriteAllText(@"C:\test.txt", output);

在线示例01:http://rextester.com/TIVM24779
在线样本02:http://rextester.com/KAUG79928

相关问题