从字符串中删除特定符号

时间:2013-07-23 11:07:04

标签: c# .net asp.net-mvc-4

我有不同的字符串,以{ }开头和结尾,如此{somestring}。我想从字符串中删除分隔符,以便它只显示somestring。我不能做任何重复字母的事情,因为我并不总是知道字符串的长度。

也许这会有所帮助。这是代码,在这里我要删除分隔符。

  private static MvcHtmlString RenderDropDownList(FieldModel model)
    {
        ISerializer serializer = new SerializeJSon();
        var value = "";
        var tb1 = new TagBuilder("select");
        tb1.MergeAttribute("id", model.QuestionId);
        tb1.MergeAttribute("name", model.QuestionId);
        tb1.MergeAttributes(GetHtmlAttributes(model.HtmlAttributes));
        tb1.AddCssClass("form-field");

        var sb = new StringBuilder();
        MatchCollection matches = RegexHelper.GetBetweenDelimiter(model.FieldValues, "{", "}");
        foreach (Match match in matches)
        {
            var o = match;  //Solution var o = match.toString();
            var tb2 = new TagBuilder("option");
          //Solution  string newString = o.trim(new [] { "{","}"});
            tb2.SetInnerText(o.ToString()); //Solution tb2.SetInnerText(newString);
            sb.Append(tb2.ToString(TagRenderMode.Normal) + "\n");
        }

        tb1.InnerHtml = sb.ToString();
        return new MvcHtmlString(tb1.ToString(TagRenderMode.Normal));
    }

3 个答案:

答案 0 :(得分:1)

您可以使用Replace

吗?
string somestring = somestring.Replace("{","").Replace("}","");

或者,您可以使用StartsWithEndsWith,它们只会从字符串的开头和结尾删除,例如:

string foo = "{something}";
if (foo.StartsWith("{"))
{
    foo = foo.Remove(0, 1);
}
if (foo.EndsWith("}"))
{
    foo = foo.Remove(foo.Length-1, 1);
}

答案 1 :(得分:1)

string newString = originalString.Trim(new[] {'{', '}'});

答案 2 :(得分:-1)

您可以使用替换例如

string someString = "{somestring}";
string someOtherString = someString.Replace("{","").Replace("}","");