如何使用struct将字母从每个字符串移动到新字符串?

时间:2019-02-07 12:29:44

标签: c# arrays string class struct

我需要创建一个结构,将每个后者从两个字符串中移出并将其移到新的字符串中。示例字符串“ world”                          字符串“书”                  输出“ wboorolkd” 我构建了该结构,但无法在此处获得我所做的输出

我是C#的新手

using System.Text;
using System.Threading.Tasks;

namespace myprogram_Struct
{
    class Program
    { 
        static void Main(string[] args)
    {
        Person person1 = new Person();
        Console.WriteLine(person1.name);
        person1.SetName("david");
        Console.WriteLine(person1.name);
        Person person2 = new Person("sarah");
        Console.WriteLine(person2.name);
        Console.ReadKey();

    }
    }
}
public struct Person
{

    public string name;
    public Person(string nm)
    {
        name = nm;
    }

    public void SetName(string newName)
    {
        name = newName;
    }
}

2 个答案:

答案 0 :(得分:3)

比@Rango的答案更生动,更幼稚的解决方案,但对于初学者而言可能更清楚。

string a = "abc";
string b = "defxyz";
StringBuilder sb = new StringBuilder();
int max = Math.Max(a.Length, b.Length);
for (int i = 0; i < max; i++)
{
    if (i < a.Length)
    {
        sb.Append(a[i]);
    }
    if (i < b.Length)
    {
        sb.Append(b[i]);
    }
}
Console.WriteLine(sb.ToString());

答案 1 :(得分:1)

我不确定这是否是您想要的,但是如果我没看错,您可以这样做:

public struct Person
{
    public string name1;
    public string name2;

    public string merge()
    {
        string retval = "";

        int length = name1.Length;

        if (length < name2.Length)
            length = name2.Length;

        for(int i = 0; i < length; i++)
        {
            if (name1.Length > i)
                retval += name1[i];

            if (name2.Length > i)
                retval += name2[i];
        }

        return retval;
    }
}