formatting string in C# - c#

How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""

If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).

Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );

If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;

Related

C# - Get All Words Between Chars

I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);

How can i use multiple delimiters in Array List

I want to ask you about the below code:
string[] seledCats = new string[0];
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue(
"CondsCats",
EzCoding.Web.RequestMethod.Post);
if (condsCats != null)
{
seledCats = condsCats.Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries);
}
After insert the selected data in the array list, output like that A1,A2,
But I want to show it like that this one 'A1','A2'
So, How can i do it ?
Thanks.
You can use this little LINQ query:
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue("CondsCats",EzCoding.Web.RequestMethod.Post);
string[] seledCats = null;
if(condsCats != null)
seledCats = condsCats
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => String.Format("'{0}'", s))
.ToArray();
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string s = "'" + string.Join("','", seledCats) + "'";
//to split into array again...
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

Insert string in regex search C#

How I can write this:
List<string> Words= new List<string>();
Regex re = new Regex(#"\b" + Words[n] + "\b");
My exactly question is how I can search elements from list or string using regex?
Possible Solution:
string testString = "cat and dog";
string[] Words = { "cat", "dog" };
foreach(string word in Words)
{
bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}
You can use all words in one regex:
var words= new List<string>();
var regex = new Regex(string.Format(#"\b(?:{0})\b", string.Join("|", words)), RegexOptions.Compiled);
This will give you a list of string regex patterns:
List<string> words= new List<string>() { "cat", "dog" };
List<string> regexPatterns = words.Select(str => "\\b" + str + "\\b").ToList();
Or if you want a list of Regex objects:
List<Regex> regexObjects = words.Select(str => new Regex("\\b" + str + "\\b")).ToList();

Adding chars before and after each word in a string

Imagine we have a string as :
String mystring = "A,B,C,D";
I would like to add an apostrophe before and after each word in my string.Such as:
"'A','B','C','D'"
How can i achieve that?
What's your definition of a word? Anything between commas?
First get the words:
var words = mystring.Split(',');
Then add the apostrophes:
words = words.Select(w => String.Format("'{0}'", w));
And turn them back into one string:
var mynewstring = String.Join(",", words);
mystring = "'" + mystring.replace(",", "','") + "'";
I would let each "word" be determined by the regex \b word boundary. So, you have:
var output = Regex.Replace("A,B,C,D", #"(\b)", #"'$1");
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();
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);
Output will be;
'A','B','C','D'
Here a DEMO.
Or more simple;
string mystring = "A,B,C,D";
Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','")));
you can use regular expressions to solve this problem
like this:
string words= "A,B,C,D";Regex reg = new Regex(#"(\w+)");words = reg.Replace(words, match=> { return string.Format("'{0}'", match.Groups[1].Value); });

C# convert DOMAIN\USER to USER#DOMAIN

I currently have the following code:
string user = #"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "#" + parts[0];
Input string user can be in one of two formats:
DOMAIN\USER
DOMAIN\\USER (with a double slash)
Whats the most elegant way in C# to convert either one of these strings to:
USER#DOMAIN
Not sure you would call this most elegant:
string[] parts = user.Split(new string[] {"/"},
StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}#{1}", parts[1], parts[0]);
How about this:
string user = #"DOMAIN//USER";
Regex pattern = new Regex("[/]+");
var sp = pattern.Split(user);
user = sp[1] + "#" + sp[0];
Console.WriteLine(user);
A variation on Oded's answer might use Array.Reverse:
string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("#",parts);
Alternatively, could use linq (based on here):
return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
.Aggregate((current, next) => next + "#" + current);
You may try this:
String[] parts = user.Split(new String[] {#"\", #"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}#{1}", parts[1], parts[0]);
For the sake of adding another option, here it is:
string user = #"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "#" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));

Categories