简体   繁体   中英

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 = type.Replace("TRIM", "RTRIM"); 
    StringBuilder builder =newStringBuilder();
    builder.AppendLine(" .....bla bla..."); 
    if (type.Trim() != ""){
    builder.AppendLine(@"   WHERE ({0}) ");
    }

The database current {0} values are

  1. TRIM(VL9) LIKE '{1}%'
  2. TRIM(VL7) LIKE '{0}%' 3.(TRIM(VL9) LIKE '{0}%'))
  3. (VL9 LIKE '{1}%' AND (TRIM(VL9) LIKE '{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.

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 )

Below code will only run if there is no "RTRIM" in type:

    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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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