单引号后替换字符

时间:2012-11-02 00:53:49

标签: c# asp.net

我使用以下C#代码在单引号后将小写字母修改为大写:

public virtual string FirstName
{
    get { return _firstName; }
    set
    {
        if (value != null)
        {
            int pos = value.IndexOf("'", 0);
            int strlength = value.Length - 1;
            if (pos >= 0 && pos != strlength)
            {
                string temp = value[pos + 1].ToString();
                temp = temp.ToUpper();
                value = value.Remove(pos + 1, 1);
                value = value.Insert(pos + 1, temp);
            }
        }
    }
}

对我而言,这看起来有点矫枉过正。是否有更简单的方法来实现预期的结果:

Value: Mc'donald
Expected: Mc'Donald

3 个答案:

答案 0 :(得分:2)

由于您对Regex持开放态度,Regex.Replace的这种超载是否会满足您的要求?

Regex.Replace Method (String, MatchEvaluator)

以下是上述链接中给出的示例的修改版本。我已将其更改为使用'\w模式并以大写形式返回匹配。

using System;
using System.Text.RegularExpressions;

class RegExSample
{
static string CapText(Match m)
    {
        // Return the match in upper case
        return m.ToString().ToUpperInvariant();
    }

    static void Main()
    {
        string text = "Mc'donald";

        System.Console.WriteLine("text=[" + text + "]");

        Regex rx = new Regex(@"'\w");

        string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));

        System.Console.WriteLine("result=[" + result + "]");
    }
}

答案 1 :(得分:2)

这里没有正则表达式

  int pos = data.IndexOf("'");
  if (pos >= 0 && pos < data.Length - 1)
  {
    StringBuilder sbl = new StringBuilder(data);
    sbl[pos + 1] = char.ToUpper(sbl[pos + 1]);
    data = sbl.ToString();
  }

答案 2 :(得分:1)

也许是正则表达式?

string value = "Mc'donald";
string found = Regex.Match(value, "'[\\w]").Value;
string result = value.Replace(found, found.ToUpper());

Console.WriteLine(result); // Mc'Donald