How can I split and prepend text? - c#

I have a string like this in C#:
string a = "A|B|C|D"
I want to split this string on the pipe character and prepend some text to each entry. Currently, I am doing a split like this:
string[] result = a.Split('|')
But because the string array is of a fixed size, I need to create a new array and copy the prepended result using a for loop. Is there a Linq way or a one-liner to achieve this instead of writing a for loop? In Python, I would have done a one-liner for loop:
newresult = ["Prepend string " + x for x in result]
Any suggestions?

var newResult = a.Split('|').Select(x => "Prepend string " + x).ToArray();

I found this to be easy enough, if you say want to join it back too:
string.Join(" , ", devices.Select(s => "PREFIX = " + s).ToArray());

Not sure why you need to create a new array, but first the Linq method is to use the .Select operator:
stirng[] result = a.Split('|').Select(x => "Prepend string " + x).ToArray();
That said, you could also just edit the array inline (i.e. no need for a new array):
for (var i = 0; i < result.Length; i++)
result[i] = "Prepend string " + result[i];

Related

How to remove comma on a for loop?

I want to remove the first comma. Is there a way to remove the comma of the loop?
Here's my code:
foreach (var field in tablefields.Items)
{
if (m_datacount < datatype.Items.Count)
{
d_type = datatype.Items[m_datacount].ToString();
m_datacount++;
}
richTextBox1.Text = richTextBox1.Text + "\t,#" + field + " " + d_type + "\n";
datatype.ResetText();
}
m_datacount = 0;
Output:
,#id uniqueidentifier
,#title varchar
,#active_flag bit
,#created_by_id uniqueidentifier
,#created_by_system_code varchar
,#created_date_time datetime
,#modified_by_id uniqueidentifier
,#modified_by_system_code varchar
,#modified_date_time datetime
Why reinvent the wheel....
Simply use String.Join
string result = String.Join(", ", myarray);
for e.g.
string[] myarray = { "Firstuser", "Seconduser" };
So result will be "Firstuser, Seconduser",
I would use String.Join. Since you have commented on another answer that tablefields is a ListBox this works:
var strings = tablefields.Items.Cast<object>().Select(o => o.ToString());
richTextBox1.Text = String.Join(Environment.NewLine + ",", strings);
Tested with this sample data:
tablefields.Items.AddRange(new ListBox.ObjectCollection(tablefields, new[]{"id","spid","charge_type_rcd","name_e","active_status"}));
Output:
id
,spid
,charge_type_rcd
,name_e
,active_status
You can also use a StringBuilder which is less readable but can be more efficient if you have many, many items:
StringBuilder sb = new StringBuilder();
foreach (var item in tablefields.Items)
sb.AppendLine(item.ToString()).Append(',');
if (sb.Length > 0) sb.Length--; // to remove the last comma
richTextBox1.Text = sb.ToString();
TrimEnd method can be used to remove trailing characters from a string:
richTextBox1.Text = richTextBox1.Text.TrimEnd(',');
you can use below menioned code
richTextBox1.Text = richTextBox1.Text.Substring(0,richTextBox1.Text.Length-1);
What is the purpose of field2? It isn't used in your code...
Why use a counter (m_fieldcount) if you're using a foreach loop?
What does tablefields.ResetText(); do?
Anyway, try this:
richTextBox1.Text = String.Join("\n\t,", tablefields.Items.Select(a=>a.ToString()).ToArray());
richTextBox1.Text + "" + t_fields + "\n\t,".Remove(richTextBox1.Text.Lenght - 1);
check out also removing the last index. using Remove(index)

How to get string after specific string?

How to get string after text "playlist:" ?
var YT= "tag:youtube.com,2008:user:hollywoodlife09:playlist:PLDovhwKa3P88MwGzYxMDMfiAiiEWxAJYj" ;
What I did :
string[] s = YT.Split(':');
But it will give me array i.e s[0],s[1] ... and I am searching for something which can give result after specific text.
I want string after "playlist:", I know it may be easy with Regex,but currently I don't have any idea for Regex..
You can use Substring method
var output = inputString.SubString(inputString.LastIndexOf("playlist") + 8);
Or in this case it can be done using Last method via Split:
string output = YT.Split(':').Last();
Using regex replace, remove everything before the :playlist: with empty string.
string playlist = Regex.Replace(YT, ".*:playlist:", "");
more reusably,
static IEnumerable<KeyValuePair<string, string>> SplitPairs(
this string source,
params char[] seperators)
{
var values = source.Split(seperators);
for(var i = 0; i < values.Length; i += 2)
{
yield return new KeyValuePair<string, string>(
values[i],
values[i + 1]);
}
}
so you could do,
var yTlookup = YT.SplitPairs(':').ToDictionary(p => p.Key, p => p.Value);
var playList = yTLookup["playlist"];
or if you don't want an extension,
var segments = YS.Split(new[] { ':' });
var ySlookup = Enumerable.Range(0, segemnts.Length / 2)
.ToDictionary(i => segments[i * 2], i => segments[(i * 2) + 1]);
so you can do,
var playlist = ysLookup["playlist"];
either approach pays off as soon as you want another value from the sequence.
The regex is .+playlist:([^:])

String concatenation based on best practices

I have a string,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
Now i just need to change the first "alwaysSame09102012" with "always2013forever".
I know i can do something like this,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string[] c = ij.split['/'];
string finalString = ij.replace( "/" + c[0] + "/", "/" + "always2013forever" + "/");
This is my logic but no working, please help,
only constant in my string is "/alwaysSame09102012/" which i need to replace
Update
**
What if I got this "alwaysSame09102012" in at of my query string,
that's why I don't want to use replace.
**
Use String.Replace.
Ex:
var goodStr = ij.Replace("alwaysSame09102012", "always2013forever");
The reason your answer does not work is because c[0] is going to be "". The value you are looking for (e.g. 'alwaysSame09102012') is going to be in c[1].
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string newString = ij.Replace("alwaysSame09102012","always2013forever");
string ReplaceFirst (string source, string old_substring, string new_substring)
{
var position = source.IndexOf(old_substring);
return (position < 0)
? source
: source.Substring(0, position) + new_substring + source.Substring(position + old_substring.Length);
}
Usage:
var new_string = ReplaceFirst("/alwaysSame09102012/myThing...", "alwaysSame09102012","always2013forever");
You should use the URI classes.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
This will give you more flexibility, and prevent you from escaping problems etc.

Extracting parts of a string c#

In C# what would be the best way of splitting this sort of string?
%%x%%a,b,c,d
So that I end up with the value between the %% AND another variable containing everything right of the second %%
i.e. var x = "x"; var y = "a,b,c,d"
Where a,b,c.. could be an infinite comma seperated list. I need to extract the list and the value between the two double-percentage signs.
(To combat the infinite part, I thought perhaps seperating the string out to: %%x%% and a,b,c,d. At this point I can just use something like this to get X.
var tag = "%%";
var startTag = tag;
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf(tag, startIndex);
return s.Substring(startIndex, endIndex - startIndex);
Would the best approach be to use regex or use lots of indexOf and substring to do the extracting based on te static %% characters?
Given that what you want is "x,a,b,c,d" the Split() function is actually pretty powerful and regex would be overkill for this.
Here's an example:
string test = "%%x%%a,b,c,d";
string[] result = test.Split(new char[] { '%', ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result) {
Console.WriteLine(s);
}
Basicly we ask it to split by both '%' and ',' and ignore empty results (eg. the result between "%%"). Here's the result:
x
a
b
c
d
To Extract X:
If %% is always at the start then;
string s = "%%x%%a,b,c,d,h";
s = s.Substring(2,s.LastIndexOf("%%")-2);
//Console.WriteLine(s);
Else;
string s = "v,u,m,n,%%x%%a,b,c,d,h";
s = s.Substring(s.IndexOf("%%")+2,s.LastIndexOf("%%")-s.IndexOf("%%")-2);
//Console.WriteLine(s);
If you need to get them all at once then use this;
string s = "m,n,%%x%%a,b,c,d";
var myList = s.ToArray()
.Where(c=> (c != '%' && c!=','))
.Select(c=>c).ToList();
This'll let you do it all in one go:
string pattern = "^%%(.+?)%%(?:(.+?)(?:,|$))*$";
string input = "%%x%%a,b,c,d";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
// "x"
string first = match.Groups[1].Value;
// { "a", "b", "c", "d" }
string[] repeated = match.Groups[2].Captures.Cast<Capture>()
.Select(c => c.Value).ToArray();
}
You can use the char.IsLetter to get all the list of letter
string test = "%%x%%a,b,c,d";
var l = test.Where(c => char.IsLetter(c)).ToArray();
var output = string.Join(", ", l.OrderBy(c => c));
Since you want the value between the %% and everything after in separate variables and you don't need to parse the CSV, I think a RegEx solution would be your best choice.
var inputString = #"%%x%%a,b,c,d";
var regExPattern = #"^%%(?<x>.+)%%(?<csv>.+)$";
var match = Regex.Match(inputString, regExPattern);
foreach (var item in match.Groups)
{
Console.WriteLine(item);
}
The pattern has 2 named groups called x and csv, so rather than just looping, you can easily reference them by name and assign them to values:
var x = match.Groups["x"];
var y = match.Groups["csv"];

Merging strings together with separator berween them in C#

I needed to merge strings that are inside List<string> together into oneliner. I came up with simple solution but I am not sure if it's the best way to go.
First version with problematic , on string start:
string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}
Second version (Linq power) but still with ` :
string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s);
Working version without , but amount of lines makes some pain in later reading it:
int b = 0;
string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
if (b == 0) {
b = 1;
benchmarkiUjemneDatyRazem = s;
continue;
}
benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}
Final version that I came up with was based on Linq with Subsitute to first char:
string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s).Substring(1);
Is this good approach to this problem ? Or there's better way to actually do it? Like using StringBuilder or so?
If you're using .Net 4, you can use string.Join (in earlier versions this will work only if benchmarkiUjemne is a string[]):
string result = string.Join(",", benchmarkiUjemne);
If this is .Net 3.5 or older, you can still use it by calling ToArray on the list:
string result = string.Join(",", benchmarkiUjemne.ToArray());
Use string.Join:
var res = string.Join(",", benchmarkiUjemne);

Categories