编辑数组元素
我有一个驱动器号数组,我需要在每个字母后附加一个冒号,然后将该数组传递给另一个函数。我可以这样做还是需要创建一个新数组?或者也许根本不是数组而是某种列表?
string source = "C|D|E";
string[] sourcearray = source.Split('|');
foreach (string driveletter in sourcearray)
{
//need to append ":" to each drive letter
}
编辑:有时源数组可能以管道结尾:
string source = "C|D|E|";
当发生这种情况时,如果我使用公共 for 循环,数组中的最后一个元素将是冒号,但我不能这样做。如何最好地处理这个问题?当发生这种情况时,最终的数组需要看起来像:
C: D: E:
谢谢。
I have an array of drive letters and I need to append a colon to each letter and then pass the array to another function. Can I do this or do I need to create a new array? Or maybe not an array at all but some kind of List instead?
string source = "C|D|E";
string[] sourcearray = source.Split('|');
foreach (string driveletter in sourcearray)
{
//need to append ":" to each drive letter
}
EDIT: There are times when the source array could end in a pipe:
string source = "C|D|E|";
When that happens the last element in the array will be a colon if I use a common for loop, and I can't have this. How best to handle this? When this happens the final array needs to look like:
C: D: E:
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字符串是不可变的,因此您无法更改字符串实例,但必须使用新字符串更改数组槽:
Strings are immutable, so you can't change the string instance but you must change the array slots with new strings:
将 for 循环替换为
重新编辑:
这里最好的解决方案是这是 string.Split() 方法的特殊变体。不幸的是,这需要一组分隔符,所以我们得到:
Replace your for-loop with
Re the Edit:
The best solution here is to this is a special variation of the
string.Split()
method. Unfortunately that one requires an array of separator chars, so we get: