c# - 有没有办法从 txt 文件 c# 中的数字中减去

标签 c# text-files subtraction

您好,我是 C# 新手,需要一些帮助。我有一个程序,当前将事件保存到自己的文本文件中,其中包含有关事件的详细信息(详细信息由用户输入)。这些细节之一是门票数量。我在制作它时遇到了麻烦,所以当一张票被拿来时,金额会减少一个。

我想知道是否有方法可以让我从文本文件中的数字中减去 1。 这是我的文本文件的布局方式:

Event Name: Test
Event Time: 12:30
Event Location: Test
Amount Of Tickets: 120
Price Of Tickets: £5

这是我尝试过的方法,所有这一切都是将 -1 -1 添加到值而不是从值中删除:

Console.WriteLine("What Event Would You Like To Buy A Ticket For?");
            string EventUpdate = Console.ReadLine(); 
            string folderPath = (@"A:\Work\Visual Studio\TextFiles");
            string fileName = EventUpdate + ".txt";
            string filePath = folderPath + "\\" + fileName;  //creats file path using FolderPath Plus users Input
            string Contents = File.ReadAllText(filePath);
            Console.WriteLine(Contents); //displays the txt file that was called for
            Console.WriteLine("\n");
            string FindText = "Amount Of Tickets:";
            int I = -1;
            string NewText = FindText + I;
            string NewTempFile = folderPath + EventUpdate + ".txt";
            string file = filePath;
            File.WriteAllText(file, File.ReadAllText(file).Replace(FindText, NewText));


            using (var sourceFile = File.OpenText(file))
            {
                // Create a temporary file path where we can write modify lines
                string tempFile = Path.Combine(Path.GetDirectoryName(file), NewTempFile);
                // Open a stream for the temporary file
                using (var tempFileStream = new StreamWriter(tempFile))
                {
                    string line;
                    // read lines while the file has them
                    while ((line = sourceFile.ReadLine()) != null)
                    {

                        // Do the Line replacement
                        line = line.Replace(FindText, NewText);
                        // Write the modified line to the new file
                        tempFileStream.WriteLine(line);
                    }
                }
            }
            // Replace the original file with the temporary one
            File.Replace(NewTempFile, file, null);

当我使用上面的代码时,我的文本文件发生了什么:

 Event Name: Test
 Event Time: 12:30
 Event Location: Test
 Amount Of Tickets:-1-1 120
 Price Of Tickets: £5 

最佳答案

有很多方法可以做到这一点...但是,您需要将“文本数字”转换为实际数字(在本例中为 integer)以对其执行数学运算

// get the lines in an array
var lines = File.ReadAllLines(file);

// iterate through every line
for (var index = 0; index < lines.Length; index++)
{
   // does the line start with the text you expect?
   if (lines[index].StartsWith(findText))
   {
      // awesome, lets split it apart
      var parts = lines[index].Split(':');
      // part 2 (index 1) has your number
      var num = int.Parse(parts[1].Trim());
      // recreate the line minus 1
      lines[index] = $"{findText} {num-1}";
      // no more processing needed
      break;
   }    
}
// write the lines to the file
File.WriteAllLines(file, lines);

注意:即使这不起作用(而且我还没有检查过)你应该有足够的信息继续独立


其他资源

String.StartsWith Method

Determines whether the beginning of this string instance matches a specified string.

String.Split Method

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

String.Trim Method

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

Int32.Parse Method

Converts the string representation of a number to its 32-bit signed integer equivalent.

File.ReadAllLines Method

Opens a text file, reads all lines of the file into a string array, and then closes the file.

File.WriteAllLines Method

Creates a new file, writes one or more strings to the file, and then closes the file.

$ - string interpolation (C# Reference)

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

关于c# - 有没有办法从 txt 文件 c# 中的数字中减去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030917/

相关文章:

c# - 在objectListView中构建treeListView的模型

C# 修改 Windows 服务的配置文件

代码页顶部的 C# using 语句

c# - 无法写入已关闭的 TextWriter

c# - 错误 "Xamarin.Android.Support.Design 27.0.2.1 is not compatible with monoandroid60"

java - 写入txt文档java中的特定行

java - 从 JTable 的文本文件中解析日期

algorithm - 在特定范围内查找两个大向量中元素之间的差异值并将其合并(对于 bsxfun 而言太大)

java - 如何使用 Java 日历从日期中减去 X 天?

MySQL - 减去表的某些行并将结果与​​其他行一起显示