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
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; }
因此,如果关键字是“Hello”.我希望这个输出/ h / e / l / l / o但是目前它只输出最后一个字符,在这种情况下/ o
有人可以帮忙吗?
on = vs =和String vs StringBuilder你的问题在于这一行:
kw = "/"+letters[i];
这是一个直接赋值,将覆盖上一次迭代的kw值.也许你想要=.但是,此时您需要了解StringBuilder以及为什么在循环中使用String执行会导致性能不佳.
相关问题
> String vs StringBuilder
> When to use StringBuilder?
关于正则表达式
如果您要学习正则表达式,也可以使用一行来完成.您只需匹配每个字符x并将其替换为/ x.
参考
> regular-expressions.info
> The Dot Matches (Almost) Any Character
> .NET Framework Class Library – Regex.Replace
例
这是一个应该说明的片段:
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
>正确使用时,正则表达式很棒!
参考
> C# Language Reference – foreach
> .NET Framework Developer’s Guide – Using the StringBuilder
Class
> .NET Framework 4 – Regular Expression Language Elements
附件
> Source code and output of snippet on ideone.com