如何在C#中组合字符串?
我需要组合“a”“b”“c”“d”。 我尝试将它们放入列表中,然后通过它们解析 foreach 方法,但无济于事。
我还能做什么?
I need to make a combinaion of Stings "a" "b" "c" "d".
I've tried putting them in a list then parsing a foreach methord through them, but to no avail.
What else can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将字符串放在数组中,您可以使用下面的函数打印所有排列,以便输出:abcd、abdc、adbc 等。
递归排列(来自 MSDN):
Having the strings in an array you can use the function below to print all permutations so it outputs: abcd, abdc, adbc, etc.
Recursive permutation (from MSDN):
我会给你逻辑。
创建一个
List
,然后继续向其中添加每个字符串。添加所有字符串后,然后在最小索引和最大索引之间生成一个随机数,如下所示:
然后,在使用该数字在列表上循环打印每个字符串时,务必检查是否相同随机数不会在下一次迭代中重复。
I will give you the logic.
Create a
List<String>
and then go on adding each string to it.Once you added all the strings, then generate a random number between minimum and maximum index like this :
Then, while printing each string in the loop over the List with this number, be sure to check that the same random number is not repeated for the nex iteration.
你会列一份清单吗?
你应该能够循环遍历它
Will a list do you?
You should be able to loop through that
如果你有一定数量的字符串,你可以使用,
否则 for/foreach 循环将是前进的方向,
我不会使用 string + string + string 样式连接,因为由于字符串在内存中的工作方式,这是不好的做法。
编辑:我还没有测试在浏览器中编写的代码!如果您有任何问题,请告诉我。
刚刚看到上面的评论,我发布的代码将始终以相同的顺序输出字符串,因此可能不是您想要的。
HTH
OneShot
if you have a set number of strings you could use
otherwise a for/foreach loop would be the way forward,
I wouldn't use string + string + string style concatenation as this is bad practice due to the way strings work in memory.
EDIT: I haven't tested the code it was written in the browser! let me know if you have any issues.
Just seen the comments above, the code I have posted will always output the strings in the same order so may not be what you want.
HTH
OneShot
此示例执行所有组合(正确):
输出:
如果您需要排列,您可以插入
This example does all the combinations (proper):
Output:
If you needed permutations, you can drop-in an algorithm from