C# 替换字符串中的某个字符

static string ReplaceChar(string str, char chr1, char chr2)
{
    if (str == null || str == string.Empty)
    {
        throw new Exception("String input can not be null");
    }
 
    string result = "";
 
    for (int i = 0; i < str.Length; i++)
    {
        if (str[i]!=chr1)
        {
            result += str[i];
        }
        else
        {
            result += chr2;
        }
    }
 
    return result;
}
 
static string ReplaceChar2(string str, char chr1, char chr2)
{
    if (str == null || str == string.Empty)
    {
        throw new Exception("String input can not be null");
    }
 
    char[] chrArray = str.ToCharArray();
    string result = "";
    for (int i = 0; i < chrArray.Length; i++)
    {
        if (chrArray[i] == chr1)
        {
            chrArray[i] = chr2;
        }
    }
 
    foreach (char item in chrArray)
    {
        result += item;
    }
    return result;
}

  

posted @   Ligeance  阅读(11226)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示