如何在C#中组合字符串?

发布于 2024-11-14 10:24:20 字数 80 浏览 2 评论 0原文

我需要组合“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

萌梦深 2024-11-21 10:24:21

将字符串放在数组中,您可以使用下面的函数打印所有排列,以便输出:abcd、abdc、adbc 等。

递归排列(来自 MSDN):

public static void Permute(string[] strings, int start, int finish)
  {
    if (start == finish)
    {
      for (int i = 0; i <= finish; ++i)
      {
        Console.Write(strings[i] + " " );
      }
        Console.WriteLine("");
    }
    else
    {
      for (int i = start; i <= finish; ++i)
      {
        string temp = strings[start];
        strings[start] = strings[i];
        strings[i] = temp;

        Permute(strings, start+1, finish);

        temp = strings[start];
        strings[start] = strings[i];
        strings[i] = temp;
      }
    }

  }  // Permute()

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

public static void Permute(string[] strings, int start, int finish)
  {
    if (start == finish)
    {
      for (int i = 0; i <= finish; ++i)
      {
        Console.Write(strings[i] + " " );
      }
        Console.WriteLine("");
    }
    else
    {
      for (int i = start; i <= finish; ++i)
      {
        string temp = strings[start];
        strings[start] = strings[i];
        strings[i] = temp;

        Permute(strings, start+1, finish);

        temp = strings[start];
        strings[start] = strings[i];
        strings[i] = temp;
      }
    }

  }  // Permute()
走野 2024-11-21 10:24:21

我会给你逻辑。

创建一个 List,然后继续向其中添加每个字符串。

List<String> s = new List<String>();  

s.add("a");
s.add("b");
s.add("c");
s.add("d");  

添加所有字符串后,然后在最小索引和最大索引之间生成一个随机数,如下所示:

private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max); 
}  

然后,在使用该数字在列表上循环打印每个字符串时,务必检查是否相同随机数不会在下一次迭代中重复。

I will give you the logic.

Create a List<String> and then go on adding each string to it.

List<String> s = new List<String>();  

s.add("a");
s.add("b");
s.add("c");
s.add("d");  

Once you added all the strings, then generate a random number between minimum and maximum index like this :

private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max); 
}  

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.

泅渡 2024-11-21 10:24:21

你会列一份清单吗?

List<String>myStrings = new List<String>();

myStrings.Add("a");
...
myStrings.Add("d");

你应该能够循环遍历它

Will a list do you?

List<String>myStrings = new List<String>();

myStrings.Add("a");
...
myStrings.Add("d");

You should be able to loop through that

魂ガ小子 2024-11-21 10:24:21

如果你有一定数量的字符串,你可以使用,

var s = String.Format("{0}{1}{2}{3}", stringA, stringB, stringC, stringD);

否则 for/foreach 循环将是前进的方向,

var sb = new StringBuilder();
var strings = new List<string>();

// Add strings to list

for (var i = 0; i < strings.Count; i++)
{
    sb.Append(strings[i]);
}

var s = sb.ToString();

我不会使用 string + string + string 样式连接,因为由于字符串在内存中的工作方式,这是不好的做法。

编辑:我还没有测试在浏览器中编写的代码!如果您有任何问题,请告诉我。

刚刚看到上面的评论,我发布的代码将始终以相同的顺序输出字符串,因此可能不是您想要的。

HTH

OneShot

if you have a set number of strings you could use

var s = String.Format("{0}{1}{2}{3}", stringA, stringB, stringC, stringD);

otherwise a for/foreach loop would be the way forward,

var sb = new StringBuilder();
var strings = new List<string>();

// Add strings to list

for (var i = 0; i < strings.Count; i++)
{
    sb.Append(strings[i]);
}

var s = sb.ToString();

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

岁吢 2024-11-21 10:24:21
List<String>stringList = new List<String>();

stringList.Add("a");
stringList.Add("b");
...
...

foreach(string item in stringList)
 {
   string text=item;
}
List<String>stringList = new List<String>();

stringList.Add("a");
stringList.Add("b");
...
...

foreach(string item in stringList)
 {
   string text=item;
}
平安喜乐 2024-11-21 10:24:21

此示例执行所有组合(正确):

using System;
using System.Linq;
using System.Collections.Generic;

public static class Program
{
    public static void Main(string[] args)
    {
        var list = new [] { "a", "b", "c", "d" };
        foreach (var combi in Enumerable.Repeat(list, list.Length).CartesianProduct())
            Console.WriteLine(string.Join(" ", combi));
    }

    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
    { 
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
        return sequences.Aggregate( 
                emptyProduct, 
                (accumulator, sequence) =>  
                from accseq in accumulator  
                from item in sequence  
                select accseq.Concat(new[] {item}));                
    }
}

输出:

a a a a
a a a b
a a a c
a a a d
a a b a
a a b b
a a b c
a a b d
a a c a
a a c b
....
d d b c
d d b d
d d c a
d d c b
d d c c
d d c d
d d d a
d d d b
d d d c
d d d d

如果您需要排列,您可以插入

  1. MoreLinq
  2. CodeProject http://www.codeproject.com/KB/recipes/Combinatorics.aspx

This example does all the combinations (proper):

using System;
using System.Linq;
using System.Collections.Generic;

public static class Program
{
    public static void Main(string[] args)
    {
        var list = new [] { "a", "b", "c", "d" };
        foreach (var combi in Enumerable.Repeat(list, list.Length).CartesianProduct())
            Console.WriteLine(string.Join(" ", combi));
    }

    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
    { 
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
        return sequences.Aggregate( 
                emptyProduct, 
                (accumulator, sequence) =>  
                from accseq in accumulator  
                from item in sequence  
                select accseq.Concat(new[] {item}));                
    }
}

Output:

a a a a
a a a b
a a a c
a a a d
a a b a
a a b b
a a b c
a a b d
a a c a
a a c b
....
d d b c
d d b d
d d c a
d d c b
d d c c
d d c d
d d d a
d d d b
d d d c
d d d d

If you needed permutations, you can drop-in an algorithm from

  1. MoreLinq
  2. CodeProject http://www.codeproject.com/KB/recipes/Combinatorics.aspx
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文