on =
vs +=
and String
vs StringBuilder
Your problem is in this line:
kw = "/"+letters[i];
This is a straight assignment, and will overwrite the value of kw
from the previous iteration. Perhaps you want +=
. However, at this point you need to know about StringBuilder
and why doing +=
with String
in a loop yields bad performance.
Related questions
On regular expressions
If you're up to learning regular expression, you can also do this with one line. You simply match each character x
and replace it with /x
.
References
Example
Here's a snippet that should be illustrative:
string keyword = "hello";
foreach (char ch in keyword) {
Console.Write("[" + ch + "]");
}
Console.WriteLine();
// prints "[h][e][l][l][o]"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyword.Length; i++) {
sb.Append("<" + keyword[i] + ">");
}
Console.WriteLine(sb);
// prints "<h><e><l><l><o>"
Console.WriteLine(new Regex(@"(?=.)").Replace(keyword, @"/"));
// prints "/h/e/l/l/o"
Console.WriteLine(new Regex(@"(.)").Replace(keyword, @"($1$1)"));
// prints "(hh)(ee)(ll)(ll)(oo)"
Some key ideas:
- Unless you need explicit index, use foreach loop
- When building a string in a loop, use
StringBuilder
- When properly used, regular expressions are great!
References
Attachments