[英]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:我的最终 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:您还可以简单地使用
Replace()
方法将","
的实例替换为"'',''"
,同时在字符串的两端添加"''"
:
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.Split()
,一个loop
,然后是这样的String.Join
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:您可以使用这个 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**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.