How to separate a string from characters

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 allows you to say "Hello". I want this to output / h / e / l / l / o, but for now its only output is the last character, in this case / o

Can anyone help?

+3
source share
4 answers

on =vs +=and StringvsStringBuilder

Your problem in this line:

 kw = "/"+letters[i];

This is a direct assignment and will overwrite the value kwfrom the previous iteration. Perhaps you want to +=. However, at this point you need to know about StringBuilderand why running +=c Stringin a loop leads to poor performance.

Related Questions


, . x /x.


, :

   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)"

:

  • , foreach
  • StringBuilder
  • !

+6

, .NET 4.0, :

string someString = "abc";
string result = string.Join("/", (IEnumerable<char>)someString);
+1

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;
}
0

I tried to optimize this to use less memory while working with characters.

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);
}
0
source

Source: https://habr.com/ru/post/1751119/


All Articles