Adding characters before and after each word in a string

Suppose we have a line like:

String mystring = "A,B,C,D"; 

I would like to add an apostrophe before and after each word in my line. As:

 "'A','B','C','D'" 

How can i achieve this?

+4
source share
6 answers

What is your definition of the word? Anything between the commas?

First get the words:

 var words = mystring.Split(','); 

Then add the apostrophes:

 words = words.Select(w => String.Format("'{0}'", w)); 

And put them back on one line:

 var mynewstring = String.Join(",", words); 
+7
source
 mystring = "'" + mystring.replace(",", "','") + "'"; 
+6
source

I would like each "word" to be defined by the word boundary of the regular expression \b . So you have:

 var output = Regex.Replace("A,B,C,D", @"(\b)", @"'$1"); 
+3
source
 string str = "a,b,c,d"; string.Format("'{0}'", str.Replace(",", "','")); 

or

 string str = "a,b,c,d"; StringBuilder sb = new StringBuilder(str.Length * 2 + 2); foreach (var c in str.ToCharArray()) { sb.AppendFormat((c == ',' ? "{0}" : "'{0}'"), c); } str = sb.ToString(); 
+1
source
 string mystring = "A,B,C,D"; string[] array = mystring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); string newstring = ""; foreach (var item in array) { newstring += "'" + item + "',"; } newstring = newstring.Remove(newstring.Length - 1); Console.WriteLine(newstring); 

The output will be:

 'A','B','C','D' 

Here is the demo .

Or easier:

 string mystring = "A,B,C,D"; Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','"))); 
0
source

you can use regular expressions to solve this problem for example:

string words = "A, B, C, D";
Regex reg = new Regex (@ "(\ w +)");
words = reg.Replace (words, match => {return string.Format ("'{0}'", match.Groups [1] .Value);});

0
source

Source: https://habr.com/ru/post/1487035/


All Articles