So I have a string, and in it, I want to replace last 3 chars with a dot.
I did something but my result is not what I wanted it to be.
Here is my code:
string word = "To je";
for (int k = word.Length; k > (word.Length) - 3; k--)
{
string newWord = word.Replace(word[k - 1], '.');
Console.WriteLine(newWord);
}
The output I get is:
To j.
To .e
To.je
But the output I want is:
To...
How do I get there?
So the program is doing something similar to what I actually want it to do, but not quite.
I've really been struggling with this and any help would be appreciated.
Look at this:
string newWord = word.Replace(word[k - 1], '.');
You're always replacing a single character from word
... but word
itself doesn't change, so on the next iteration the replacement has "gone".
You could use:
word = word.Replace(word[k - 1], '.');
(And then move the output to the end, just writing out word
.)
However, note that this will replace all occurrences of any of the last three characters with a .
.
The simplest way to fix all of this is to use Substring
of course, but if you really want to loop, you could use a StringBuilder
:
StringBuilder builder = new StringBuilder(word);
for (int k = word.Length; k > (word.Length) - 3; k--)
{
builder[k - 1] = '.';
}
word = builder.ToString();
See more on this question at Stackoverflow