【问题标题】:Find and replace dynamic values via for loop通过 for 循环查找和替换动态值
【发布时间】:2012-09-24 19:05:42
【问题描述】:

http://www.test.com/test.aspx?testinfo=&|&

我正在尝试用表中的值替换 &。我将姓名和年龄作为两个参数,我需要替换并获得这样的网址:

http://www.test.com/test.aspx?testinfo=name|age

如果我有 3 个字符串参数要替换为 url:

http://www.test.com/test.aspx?testinfo=&|&

上述网址的姓名、年龄、地址:

http://www.test.com/test.aspx?testinfo=name|age|address

string URL=string.Empty;
URL=http://www.test.com/test.aspx?testinfo=&|&;
//in this case fieldsCount is 2, ie. name and age
for(int i=0; i<fieldsCount.Length-1;i++)
{
      URL.Replace("*","name");
}

如何添加“年龄”以便得到?任何输入都会有所帮助。

http://www.test.com/test.aspx?testinfo=name|age

【问题讨论】:

  • 这个帖子不是很清楚。您可以尝试编辑您的帖子吗?

标签: c# asp.net .net winforms


【解决方案1】:

我想这就是你想要的,

    List<string> keys = new List<string>() { "name", "age", "param3" };
    string url = "http://www.test.com/test.aspx?testinfo=&|&;";
    Regex reg = new Regex("&");
    int count = url.Count(p => p == '&');

    for (int i = 0; i < count; i++)
    {
        if (i >= keys.Count)
            break;
        url = reg.Replace(url, keys[i], 1);
    }

【讨论】:

    【解决方案2】:

    我对两件事感到好奇。

    • 你为什么要使用 &amp; 作为替换的东西,当它有上下文时 查询字符串中的含义作为键/值之间的分隔符 对?
    • 为什么有时你的字符串只有 2 个字段 (&amp;|&amp;) 替换它的值有多于 2 个键?

    如果这些事情无关紧要,对我来说,有一个其他东西的替换字符串会更有意义......例如http://www.test.com/test.aspx?testinfo=[testinfo]。当然,您需要选择在您的 Url 中出现的可能性为 0 的东西,而不是您期望的位置。然后,您可以将其替换为以下内容:

    url = url.Replace("[testinfo]", string.Join("|", fieldsCount));
    

    请注意,这不需要您的 for 循环,并且应该会产生您预期的 url。 请参阅 msdn 上的 string.Join

    使用指定的连接字符串数组的所有元素 每个元素之间的分隔符。

    【讨论】:

      【解决方案3】:

      如果我理解正确,我认为你需要这样的东西:

      private static string SubstituteAmpersands(string url, string[] substitutes)
      {
          StringBuilder result = new StringBuilder();
          int substitutesIndex = 0;
      
          foreach (char c in url)
          {
              if (c == '&' && substitutesIndex < substitutes.Length)
                  result.Append(substitutes[substitutesIndex++]);
              else
                  result.Append(c);
          }
      
          return result.ToString();
      }
      

      【讨论】:

        最近更新 更多