简体   繁体   中英

How to split string and add custom character in c#

I have following strings:

   str1 - 12345,67890,9999,0000
   str2 - 5839 

Now i want to split, add character and join string again.

My final output:

str1 -  ''12345'',''67890'',''9999'',''0000''
str2 -  ''5839''

You can also simply use the Replace() method to replace instances of "," with "'',''" , while also adding "''" to both ends of the string:

var input = "12345,67890,9999,0000";

var result = $"''{input.Replace(",", "'',''")}''";

// result == "''12345'',''67890'',''9999'',''0000''"

The simplest way would be using String.Split() , a loop and then String.Join like this

string str1  =   "12345,67890,9999,0000";
var strArr = str1.Split(',');

for(int i=0; i<strArr.Length;i++){

    strArr[i] = "''"+strArr[i]+"''";
}
Console.WriteLine(String.Join(",", strArr));  

// output = ''12345'',''67890'',''9999'',''0000''

The code sample below

var str1 = "12345,67890,9999,0000";
var str2 = "5839";
var result1 = "''" + string.Join("'',''", str1.Split(',')) + "''";
var result2 = "''" + string.Join("'',''", str2.Split(',')) + "''";
Console.WriteLine(result1);
Console.WriteLine(result2);

You can use this function:

public string splitFunction(string strAttached, string strSpecialChar, char chrSplitChar = ',', bool blnTrimValues = true)
{
    try
    {
        IEnumerable<string> result;

        if (blnTrimValues)
            result = strAttached.Split(chrSplitChar).Select(strValue => strSpecialChar + (string)strValue.Trim() + strSpecialChar);
        else if (strSpecialChar == "")
            result = strAttached.Split(chrSplitChar);
        else
            result = strAttached.Split(chrSplitChar).Select(strValue => strSpecialChar + strValue + strSpecialChar);

        return string.Join(chrSplitChar.ToString(), result);
    }
    catch (Exception ex) { throw ex; }
}

Usage and results:

string res = splitFunction("12345,67890,9999 ,0000 ", "''", ',', true);
// Result: ''12345'',''67890'',''9999'',''0000''

string res = splitFunction("5839", "''", ',', true);
// Result: ''5839''

string res = splitFunction("A,B,C,D", "$", ',', true);
// Result: $A$,$B$,$C$,$D$

string res = splitFunction("Val1, Val2, Val3, Val4", "**");
// Result: **Val1**,**Val2**,**Val3**,**Val4**

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