111,093
社区成员




public string ReplaceItems(string str, List<string> items)
{
string textToReplace = str;
Regex reg = new Regex(@"\{([^{}]+)\}");
foeach(string item in items)
{
textToReplace = reg.Replace(textToReplace, item, 1);
}
return textToReplace;
}
List<string> people = new List<string> { "Tom", "Jack", "Charlie"};
int i= 0;
while (a.Contains("{")) //循环替换所有的“{”及内部内容。
{
string oldStr = strTemp.Substring(a.IndexOf("{"), a.IndexOf("}") - a.IndexOf("{") + 1); //获取第一个 {xxx}
a= a.Replace(oldStr, people[i]);
i++;
}
public string ReplaceItems(string str, List<string> items)
{
int k = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '{')
{
while (i < str.Length && str[i] != '}') i++;
sb.Append(items[k++]);
}
else if (str[i] != '}') sb.Append(str[i]);
}
return sb.ToString();
}
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string s = "{someone}'s wallet was stolen by {someone else} but the police who called {anyone} caught him.";
Dictionary<string, string> rule = new Dictionary<string, string>();
rule.Add("someone", "Tom");
rule.Add("someone else", "Jack");
rule.Add("anyone", "Charlie");
string result = RuleReplace(s, rule);
Console.WriteLine(result);
Console.ReadKey();
}
/// <summary>
/// 特定的字符串替换方法
/// </summary>
/// <param name="src">原字符串</param>
/// <param name="rule">替换规则</param>
/// <returns>替换后的结果字符串</returns>
public static string RuleReplace(string src, Dictionary<string, string> rule)
{
return Regex.Replace(src, @"\{([^{}]+)\}", delegate(Match m)
{
if (rule.ContainsKey(m.Groups[1].Value))
{
return rule[m.Groups[1].Value];//返回替换掉的字符串
}
return m.Value;//原样返回
});
}
}
public string ReplaceItems(string str, List<string> items)
{
int l = 0, r = 0;
int n = items.Count;
string temp = "";
for (int i = 0; i < n; i++)
{
l = str.IndexOf("{", r);
temp += str.Substring(r, l - r);
temp += items[i];
r = str.IndexOf("}", l) + 1;
}
temp += str.Substring(r, str.Length - r);
return temp;
}