views:

81

answers:

4
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?

+6  A: 

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

polygenelubricants
I have found the answer; Please see my comment.
Asyk
+1  A: 

Or, if you use .NET 4.0, you can do this:

string someString = "abc";
string result = string.Join("/", (IEnumerable<char>)someString);
Xavier Poinas
A: 

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;
}
IBhadelia
A: 

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);
}
Paw Baltzersen