如何用c#中的另一个字符串替换数据表字段的子字符串

时间:2013-02-18 04:44:35

标签: c# replace datatable

我的数据表为enter image description here

我想用一个基于cust_Id的字符串替换所有estm_suffix值的ESM。 我正在检索字符串

       for (int i=0; i < dtRefNos.Rows.Count; i++)
        {
            intCustId = int.Parse(dtRefNos.Rows[i]["cust_Id"].ToString());
            dsCustmr = custDCCls.FillCustDataSet(intCustId);
            string shrtName = dsCustmr.Tables[0].Rows[0]["cust_Sname"].ToString();
        }

不是我想只将estm_suffix中的ESM子串替换为shrtName为ESM / 00001 / 12-13到shrtName / 00001 / 12-13并且必须返回数据表。请有人帮助我。

2 个答案:

答案 0 :(得分:2)

征求意见

  

每一行都有各自的shrtNames

  

我不想替换estm_sufffix的所有值。我想要   仅替换ESM / 00001 / 12-13

中的ESM子字符串

您可以在for循环中再添加一行,使用string.Replaceestm_suffix值替换为shrtName,例如:

for (int i=0; i < dtRefNos.Rows.Count; i++)
        {
            intCustId = int.Parse(dtRefNos.Rows[i]["cust_Id"].ToString());
            dsCustmr = custDCCls.FillCustDataSet(intCustId);
            string shrtName = dsCustmr.Tables[0].Rows[0]["cust_Sname"].ToString();
            //New Line
            dtRefNos.Rows[i]["estm_suffix"] = dtRefNos.Rows[i].Field<string>("estm_suffix")
                                          .Replace("ESM", shrtName);
        }

答案 1 :(得分:1)

只需使用正则表达式。

using System.Text.RegularExpressions;

for (int i=0; i < dtRefNos.Rows.Count; i++)
{
    intCustId = int.Parse(dtRefNos.Rows[i]["cust_Id"].ToString());
    dsCustmr = custDCCls.FillCustDataSet(intCustId);
    string shrtName = dsCustmr.Tables[0].Rows[0]["cust_Sname"].ToString();
    string str = dtRefNos.Rows[i]["estm_suffix"].toString();
    str = Regex.Replace(str, "ESM", dtRefNos.Rows[i]["shrtName"].toString());
    dtRefNos.Rows[i]["estm_suffix"] = str;
}