c# - 根据字符索引合并两个字符串

标签 c# string

我正在尝试编写代码以根据字符索引合并两个字符串。例如,如果我们有两个字符串“abc”和“defg”,我想要一个字符串输出 1(合并两个字符串的所有偶数字符) ="adcf"和另一个字符串 output2="beg"(剩下的所有单词)。

我尝试了什么-

 class Program
    {
        static void Main(string[] args)

        {
            string a= "First";
                string b= "MiddleName";
                string newstring = "";
             string newstring1 = "";
                int length = b.Length;
                for (int l = 0; l < length; l=l+1)
                {
                    if(l%2==0)
                    {
                    newstring = newstring + a[l].ToString() + b[l].ToString();
                }
                    if (l % 2 == 1)
                    {
                        newstring1 = newstring1 + a[l].ToString() + b[l].ToString();
                    }
                }
            Console.ReadLine();
        }


    }

但是在这种情况下,它会在绑定(bind)数组之外给出异常。有没有更好的方法来做到这一点?

谢谢

最佳答案

我建议提取一个方法,您应该在其中解决合并两个字符串的一般性问题,从开始,每个step个字符>偏移量:

private static String Merge(String left, String right, int step, int offset) {
  StringBuilder sb = new StringBuilder();

  if (null == left)
    left = ""; // or throw exception

  if (null == right)
    right = ""; // or throw exception

  for (int i = offset; i < Math.Max(left.Length, right.Length); i += step) {
    //DONE: do not forget to check if you can get a character
    if (i < left.Length)
      sb.Append(left[i]);

    //DONE: do not forget to check if you can get a character
    if (i < right.Length)
      sb.Append(right[i]);
  }

  return sb.ToString();
}

所以你可以这样说

 String a = "abc";
 String b = "defg";

 // adcf 
 String output1 = Merge(a, b, 2, 0); 
 // beg
 String output2 = Merge(a, b, 2, 1);

关于c# - 根据字符索引合并两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675550/

相关文章:

c# - 在没有用户名的情况下连接到 SignalR 中的特定用户

c# - 评估需要一个线程临时运行。使用 Watch 窗口执行评估

java - 读入的文本与指定的文本不同

c# - 为什么 int 不能为空?可为空的 int(int?)如何在 C# 中工作?

c# - Controller Action 中的多个角色

java - 在 Java 8 中,有什么优雅的方法可以从字符串中删除某些重复的单词

c - 尝试用空格拆分 C 中的字符串并使用第二个单词

c++ - 在 C++ 中实现这种工作流程的最佳方式?

c - 由于 snprintf 而尾随零

c# - "An invalid or incomplete configuration was used while creating a SessionFactory"Web 服务中的 NHibernate