0
enter image description here使用C#如何在.txt文件中特定行中更改特定字符(基於位置)?使用C#如何在.txt文件中特定行中更改特定字符(基於位置)
enter image description here使用C#如何在.txt文件中特定行中更改特定字符(基於位置)?使用C#如何在.txt文件中特定行中更改特定字符(基於位置)
如果你知道行索引,您可以使用:
// 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);
更新(基於新的問題的詳細信息)
你提的問題是關於改變particolar基於串(不是字符)在特定行的位置。您的功能可能是:
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。
這些是我有的參數(string filePath,int lineNumber,int StartingCharacterPosition,Int replaceWordLength,string replaceWord) –
顯示您到目前爲止嘗試過的代碼。 – Lifewithsun
提供更多細節!示例輸入! –