如何将字符串分割成字符
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
有人可以帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
=
与+=
和String
与StringBuilder
上您的问题在于这一行:
这是一个直接赋值,并将覆盖上一次迭代中的
kw
值。也许您想要+=
。但是,此时您需要了解StringBuilder
以及为什么在循环中使用String
执行+=
会产生糟糕的性能。相关问题
关于正则表达式
如果您准备学习正则表达式,您也可以用一行来完成此操作。您只需匹配每个字符
x
并将其替换为/x
即可。参考文献
Regex .Replace
示例
下面是一个应该具有说明性的代码片段:
一些关键思想:
StringBuilder
参考资料
StringBuilder 类
附件
on
=
vs+=
andString
vsStringBuilder
Your problem is in this line:
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 aboutStringBuilder
and why doing+=
withString
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
Regex.Replace
Example
Here's a snippet that should be illustrative:
Some key ideas:
StringBuilder
References
StringBuilder
ClassAttachments
或者,如果您使用 .NET 4.0,则可以执行以下操作:
Or, if you use .NET 4.0, you can do this:
用这个
Use this
我尝试通过使用字符来优化它以使用更少的内存。
I tried to optimize this to use less memory by working with chars.