简体   繁体   English

在C#中可以使用什么代替字符串替换

[英]What can be used instead of string replace in C#

I am currently using string replace in some parts of the code type = type.Replace("TRIM", "RTRIM"); 我目前在代码类型= type.Replace("TRIM", "RTRIM");某些部分中使用字符串替换= type.Replace("TRIM", "RTRIM");

 type = type.Replace("TRIM", "RTRIM"); 
    StringBuilder builder =newStringBuilder();
    builder.AppendLine(" .....bla bla..."); 
    if (type.Trim() != ""){
    builder.AppendLine(@"   WHERE ({0}) ");
    }

The database current {0} values are 数据库当前的{0}值是

  1. TRIM(VL9) LIKE '{1}%' TRIM(VL9)喜欢'{1}%'
  2. TRIM(VL7) LIKE '{0}%' 3.(TRIM(VL9) LIKE '{0}%')) TRIM(VL7)喜欢'{0}%'3.(TRIM(VL9)喜欢'{0}%'))
  3. (VL9 LIKE '{1}%' AND (TRIM(VL9) LIKE '{0}%') ) (VL9像'{1}%'AND(TRIM(VL9)像'{0}%'))

This is a huge database, and the replace function is used in many files at many places. 这是一个巨大的数据库,替换功能在许多地方的许多文件中使用。 In future they will change TRIM 's to RTRIM 's in the database so then in the code(.cs files) replace string becomes RRTRIM which gives us an error. 将来他们会将数据库中的TRIM更改为RTRIM ,因此在代码(.cs文件)中,替换字符串变为RRTRIM ,这给我们带来了错误。

Is there any simple way to code which works now and after future changes? 有没有简单的编码方法可以在现在和将来更改后使用?

PS: originally the .cs queries were in DB2 which are now changed to SQL SERVER queries and now they will be making changes in db like changing TRIM to RTRIM ) PS:.cs查询最初在DB2中,现在已更改为SQL SERVER查询,现在它们将在db中进行更改,例如将TRIM更改为RTRIM

Below code will only run if there is no "RTRIM" in type: 仅当类型中没有“ RTRIM”时,以下代码才会运行:

    if (!type.contains("RTRIM"))
        {
            type = type.Replace("TRIM", "RTRIM"); 
            if (!type.contains("RRTRIM"))
            {
                type = type.Replace("RRTRIM", "RTRIM");
            }
            StringBuilder builder =newStringBuilder();
            builder.AppendLine(" .....bla bla..."); 
            if (type.Trim() != ""){
            builder.AppendLine(@"   WHERE ({0}) ");
            }
        }

but since you probably have places with rrtrim already, and maybe even rrrtrim you can do this: 但是由于您可能已经拥有rrtrim的地方,甚至可能是rrrtrim,也可以这样做:

type = type.Replace("TRIM", "RTRIM"); 
type = type.Replace("RRTRIM", "RTRIM");
type = type.Replace("RRRTRIM", "RTRIM");
StringBuilder builder =newStringBuilder();
builder.AppendLine(" .....bla bla..."); 
if (type.Trim() != ""){
builder.AppendLine(@"   WHERE ({0}) ");

Use regex. 使用正则表达式。 How to search and replace exact matching strings only 如何仅搜索和替换完全匹配的字符串

Another simple hack can be first replace all RTRIMs with TRIM first and then replace TRIM with RTRIM 另一个简单的技巧是,首先将所有RTRIM替换为TRIM,然后再将其替换为RTRIM

type.Replace("RTRIM","TRIM").Replace("TRIM","RTRIM")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM