Reputation: 33
public static string kw;
public String parse(String keyword)
{
this.keyword = keyword;
char[] letters = keyword.ToCharArray();
string g;
long length = System.Convert.ToInt64(keyword.Length.ToString());
for (int i = 0; i <= length-1; i++)
{
kw = "/"+letters[i];
}
return kw;
}
So if the keyword is lets say, "Hello". I want this to output /h/e/l/l/o but at the moment its only outputting the last character, in this case /o
Can someone help?
Upvotes: 3
Views: 482
Reputation: 2752
I tried to optimize this to use less memory by working with chars.
public string Parse(string input)
{
char[] arrResult = new char[input.Length*2];
int i = 0;
Array.ForEach<char>(input.ToCharArray(), delegate(char c)
{
arrResult[i++] = '/';
arrResult[i++] = c;
});
return new string(arrResult);
}
Upvotes: 0
Reputation: 291
Use this
public String parse(String keyword)
{
if (string.IsNullOrEmpty(keyword))
return string.Empty;
var retVal = (from v in keyword.ToArray()
select v.ToString())
.Aggregate((a, b) => a + "/" +b);
return retVal;
}
Upvotes: 0
Reputation: 383926
=
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.
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
.
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:
StringBuilder
StringBuilder
ClassUpvotes: 6
Reputation: 19743
Or, if you use .NET 4.0, you can do this:
string someString = "abc";
string result = string.Join("/", (IEnumerable<char>)someString);
Upvotes: 1