【发布时间】:2018-01-09 05:03:38
【问题描述】:
enter image description here使用 C# 如何更改 .txt 文件中特定行中的特定字符(基于位置)?
【问题讨论】:
-
显示到目前为止你尝试过的代码。
-
提供更多细节!!示例输入!
标签: c#
enter image description here使用 C# 如何更改 .txt 文件中特定行中的特定字符(基于位置)?
【问题讨论】:
标签: c#
如果您知道可以使用的行索引:
// 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。
【讨论】: