【问题标题】:Using C# How to change the particular character (based on position ) in particular line in .txt file [closed]使用 C# 如何更改 .txt 文件中特定行中的特定字符(基于位置)[关闭]
【发布时间】:2018-01-09 05:03:38
【问题描述】:

enter image description here使用 C# 如何更改 .txt 文件中特定行中的特定字符(基于位置)?

【问题讨论】:

  • 显示到目前为止你尝试过的代码。
  • 提供更多细节!!示例输入!

标签: c#


【解决方案1】:

如果您知道可以使用的行索引:

// Get file content as string array.
var lines = File.ReadAllLines(filePath);

var sb = new StringBuilder(lines[lineIndex]);

// Replacing character at given position
sb[CharacterIndex] = 'A';

lines[lineIndex] = sb.ToString();

// Writing new content to file
File.WriteAllLines(filePath, lines);

更新(基于新问题详情)

您的问题是关于根据特定行中的位置更改特定的 string (不是字符)。你的功能可能是:

void replaceStringAtPosition(string filePath, int lineNumber, int StartingCharacterPosition, int replaceWordLength, string replaceWord)
{
    // Get file content as string array.
    var lines = File.ReadAllLines(filePath);

    var sb = new StringBuilder(lines[lineNumber]);

    if (StartingCharacterPosition > sb.Length - 1) throw new Exception(nameof(StartingCharacterPosition) + " parameter value is greater than line length");

    int numberOfCharactersToRemove = StartingCharacterPosition + replaceWordLength > sb.Length - 1 ? sb.Length - StartingCharacterPosition : replaceWordLength;

    // Replacing string at given position
    sb.Remove(StartingCharacterPosition, numberOfCharactersToRemove);
    sb.Insert(StartingCharacterPosition, replaceWord);

    lines[lineNumber] = sb.ToString();

    // Writing new content to file
    File.WriteAllLines(filePath, lines);
}

也见this answer

【讨论】:

  • 这些是我拥有的参数(字符串文件路径,int lineNumber,int StartingCharacterPosition,Int replaceWordLength,字符串replaceWord)
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2020-05-18
  • 2020-07-25
  • 2013-06-28
  • 1970-01-01
相关资源
最近更新 更多