在 C# 中,您可以使用字符串的 'Replace' 方法来替换最后一个字符。以下是一个示例代码:

string str = 'Hello World';
string replacement = 'X';

int lastIndex = str.LastIndexOf('o');
if (lastIndex != -1)
{
    str = str.Remove(lastIndex, 1).Insert(lastIndex, replacement);
}

Console.WriteLine(str); // 输出: HellX World

在上面的代码中,我们首先使用 'LastIndexOf' 方法找到最后一个字符的索引。然后,我们使用 'Remove' 方法将最后一个字符从字符串中删除,并使用 'Insert' 方法在相同的位置插入替换字符。最后,我们打印出替换后的字符串。

这只是一个简单的示例,您可以根据需要修改代码来替换任何字符或字符串。

C# 替换最后一个字符:简单指南与代码示例

原文地址: https://www.cveoy.top/t/topic/qC9l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录