所以我有一个字符串,在其中,我想用一个点替换最后3个字符。我做了某事但我的结果不是我想要的。
这是我的代码:
string word = "To je";
for (int k = word.Length; k > (word.Length) - 3; k--)
{
string newWord = word.Replace(word[k - 1], '.');
Console.WriteLine(newWord);
}
我得到的输出是:
到j。
到.e
To.je
但我想要的输出是:
到......
如何到达那里?
所以程序正在做类似于我实际想做的事情,但并不完全。我真的很挣钱,任何帮助都会受到赞赏。
答案 0 :(得分:2)
看看这个:
string newWord = word.Replace(word[k - 1], '.');
您总是从word
替换单个字符...但word
本身并没有改变,所以在下一次迭代中,替换已经消失了## 34。
您可以使用:
word = word.Replace(word[k - 1], '.');
(然后将输出移到最后,只写出word
。)
但请注意,这将使用.
替换最后三个字符中的所有字符。
解决所有这一切的最简单方法当然是使用Substring
,但如果你真的想循环,可以使用StringBuilder
:
StringBuilder builder = new StringBuilder(word);
for (int k = word.Length; k > (word.Length) - 3; k--)
{
builder[k - 1] = '.';
}
word = builder.ToString();
答案 1 :(得分:1)
newWord
,然后再对它进行任何操作,保持word
不变。在正确调整相关字符后,您需要将其分配回word
。当然,更简单的解决方案(对你和计算机而言)只是简单地连接你所拥有的字符串的子串,它排除了最后三个字符的三个句点。
答案 2 :(得分:1)
假设字符串始终至少为3个字符,您可以将除最后三个字符之外的所有字符串子字符串,然后将三个点(句点)附加到该字符串的末尾。
string word = "To je";
string newWord = word.Substring(0, word.Length - 3); // Grabs everything but the last three chars
newWord += "..."; // Appends three dots at the end of the new string
Console.WriteLine(newWord);
注意:这假定输入字符串字至少为三个字符。如果你要提供一个较短的字符串,你需要额外检查字符串的长度。
答案 3 :(得分:0)
如果之后不需要原始单词
使用Jon Skeets方法
string word = "To je";
word = word.Substring(0,word.Length - 3);
word += "...";
Console.WriteLine(word);
答案 4 :(得分:0)
如@jon-skeet所说,你可以用子串做到这一点。以下是使用子字符串执行此操作的3种方法。
您可以使用String.Concat
string word = "To je";
word = String.Concat(word.Substring(0,word.Length-3),"...");
Console.WriteLine(word);
您可以使用+运算符
string word2 = "To je";
word2 = word2.Substring(0,word.Length-3) + "...";
Console.WriteLine(word2);
您可以使用String.Format
string word3 = "To je";
word3 = String.Format("{0}...",word3.Substring(0,word.Length-3));
Console.WriteLine(word3);
答案 5 :(得分:0)
我对派对来说有点晚了,但到目前为止发布的所有其他解决方案都没有优雅地处理字符串短于请求的替换次数或任意数量的替换的情况。以下是使用用户指定值替换字符串末尾的最后 n 字符的常规函数:
static String replace_last_n(String s, int nchars, char replacement='.')
{
nchars = Math.Min(s.Length, nchars > 0 ? nchars : 0);
return s.Substring(0, s.Length - nchars) + new String(replacement, nchars);
}
Console.WriteLine(replace_last_n("wow wow wow", 3));
Console.WriteLine(replace_last_n("wow", 3, 'x'));
Console.WriteLine(replace_last_n("", 3));
Console.WriteLine(replace_last_n("w", 3));
Console.WriteLine(replace_last_n("wow", 0));
Console.WriteLine(replace_last_n("wow", -2));
Console.WriteLine(replace_last_n("wow", 33, '-'));
输出:
wow wow ...
xxx
.
wow
wow
---
答案 6 :(得分:-1)
if (word.Length > 3)
Console.WriteLine(word.substring(0, word.Length - 3) + "...");
或类似的东西,不需要循环!