I need help. I tried to split a String, but I did not find the perfect way.
Example:
string data = "Car1#4$doors&1$engine&100$horsepower&2$color"
I want to split this string. The result is also a string and should look like 4 doors, 1 engine, 100 horsepower, 2 color.
Any ideas?
var res = string.Join(", ", data.Substring(data.IndexOf("#") + 1).Replace("$", " ").Split('&'));
Here's the ugliest line I could come up with to answer your question.
Enjoy!
Console.WriteLine(string.Join("\r\n", "Car1#4$doors&1$engine&100$horsepower&2$color".Split('#').Select(s => s.Replace("&", ", ").Replace('$', ' '))));
Here is one implementation, of course you can remove the matching {0}
string data = "Car1#4$doors&1$engine&100$horsepower&2$color";
string[] dataArray = data.Split('#');
string carProperties = dataArray[1].Replace("$", " ").Replace('&', ',');
Console.WriteLine("{0} {1}", dataArray[0], carProperties);
Related
Sorry for the dumb question, but I am having a bit of trouble with this. I would like to return
"James, Sam, Amanda"
but I am getting
"{ nameA = James, nameB = Sam, NameC = Amanda },"
Little help for a slow guy?
string str = String.Join(",", lst.Select(s => new { s.nameA, s.nameB, s.nameC }));
String.Join concatenates all the elements of a string array, using the delimiter you provide.
So, just send your list to an array:
string str = String.Join(",",lst.ToArray());
Also:
string str = String.Join(",", new[] { s.nameA, s.nameB, s.nameC });
Assuming that you have a list of string
you can do
string str = String.Join(",",lst.ToArray());
if lst contains your names, you just need
string str = String.Join(", ", lst.ToArray());
Just use the string.Format instead of.
string result = string.Format("{0},{1},{2}", lst.ToArray());
Here's what I'm trying to workout split function.
The com is a string passed from a textbox, and it removes the first piece from the text.
The text in the textbox is being pass as this ".fedex TYU-123 Time to pick up package"
Then, when gms is part of the first piece of the strip[] array.
string format = com.Remove(0,1);
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = strip[2];
}
strip[2] only contains "Time". I wanted to return the last part as this: "Time to pick up package".
Keep in mind also, since the message will be different at times as well, so I don't want a specific string search.
How can I achieve this?
It sounds like you only want to split the first three elements.
Split() has an overload that lets you tell it how many items to return:
format.Split(new[] { ' ' }, 3)
I assume you want all words starting with the third, use string.Join(" ", strip.Skip(2)):
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = string.Join(" ", strip.Skip(2)); //Time to pick up package
}
You can use the string.Split(char[], int32) method for this, in which you can give a max. number of splitted strings to return.
So:
format.Split(new[] {' '}, 3);
would do the trick.
More info: http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
I have a int array with for example {1,2,3,4} value.
I want to put this numbers into, for example, my list box like this :
listBox2.Items.Add("After Inserting (" + page[i].ToString() + ')' + <use all my numbers like this : 1234 here>+"Page Fault = " + pf.ToString());
Output :
After Inserting (3) 1234 page fault = 5
1234 is just an example. My array is much bigger.
How can I do that in c#?
You can use String.Join (actually the IEnumerable<T> overload is taken):
String joined = String.Join("", yourArray);
i'm new in c# how i dont know how place the string among the text
You can use String.Format to build the text and to increase readability:
var inserted = page[i].ToString();
var allInserted = String.Join("", yourArray);
var pageFault = pf.ToString();
var itemText = String.Format("After Inserting ({0}) {1} page fault = {2}"
,inserted, allInserted, pageFault);
listBox2.Items.Add(itemText);
Edit 2:
can i replace some Character instead one number in array? my array :
{1,2,3,4,-1"} output : 1,2,3,4,empty
Yes, you can replace the output:
String.Join("", yourArray.Where(i => i != -1));
Edit 3:
i understand how i can exclude -1 but i didn't understand how i can
replace something with that...like "empty" instead -1
Here we go ...
String.Join(", ", intArray.Select(i => i == -1 ? "empty" : i.ToString()));
string.Join(", ", intArray.Select(i => i.ToString()))
string.Join works also with ToList()
int[] numbers = new int[] {1,2,3,4,5};
string s = string.Join("", numbers.ToList());
Console.WriteLine(s);
output is = "12345"
EDIT: I don't know the name of your array, so I still use the above numbers example
listBox2.Items.Add("After Inserting (" + page[i].ToString() + ") " +
string.Join("", numbers.ToList()) +
" Page Fault = " + pf.ToString());
EDIT:
To exclude numbers like -1 then
int[] numeri = new int[] {1,2,3,4,5,-1};
string s = string.Join(",", numeri.Where(i => i != -1).ToList());
Console.WriteLine(s);
Note, added a comma to separate the numbers
I have an List<string> that I am iterating through and splitting on each item then adding it to a StringBuilder.
foreach(string part in List)
{
StringBuilder.Append(part.Split(':')[1] + " ");
}
So my question is how many strings are created by doing this split? All of the splits are going to produce two items. So... I was thinking that it will create a string[2] and then an empty string. But, does it then create the concatenation of the string[1] + " " and then add it to the StringBuilder or is this optimized?
The code is actually equivalent to this:
foreach(string part in myList)
{
sb.Append(string.Concat(part.Split(':')[1], " "));
}
So yes, an additional string, representing the concatenation of the second part of the split and the empty string will be created.
Including the original string, you also have the two created by the call to Split(), and a reference to the literal string " ", which will be loaded from the assembly metadata.
You can save yourself the call to Concat() by just Appending the split result and the empty string sequentially:
sb.Append(part.Split(':')[1]).Append(" ");
Note that if you are only using string literals, then the compiler will make one optimzation for you:
sb.Append("This is " + "one string");
is actually compiled to
sb.Append("This is one string");
3 extra strings for every item
part[0];
part[1];
part[1] + " "
the least allocations possible would be to avoid all the temporary allocations completely, but the usual micro-optimization caveats apply.
var start = part.IndexOf(':') + 1;
stringbuilder.Append(part, start, part.Length-start).Append(' ');
You have the original string 'split' - 1 string
You have the 'split' split into two - 2 string
You have the two parts of split joined - 1 string
The string builder does not create a new string.
The current code uses 4 strings, including the original.
If you want to save one string do:
StringBuilder.Append(part.Split(':')[1]);
StringBuilder.Append(" ");
This code:
foreach(string part in List)
{
StringBuilder.Append(part.Split(':')[1] + " ");
}
Is equivalent to:
foreach(string part in List)
{
string tmp = string.Concat(part.Split(':')[1], " ");
StringBuilder.Append(tmp);
}
So yes, it's creating a string needlessly. This would be better, at least in terms of the number of strings generated:
foreach(string part in List)
{
StringBuilder.Append(part.Split(':')[1])
.Append(" ");
}
So for each value in the list (n, known as part in your code) you are allocating:
x (I assume 2) strings for the split.
n strings for the concatenation.
Roughly n + 1 string for the StringBuilder; probably much less though.
So you have nx + n + n + 1 at the end, and assuming the split always results in two values 4n + 1.
One way to improve this would be:
foreach(string part in List)
{
var val = part.Split(':')[1];
StringBuilder.EnsureCapacity(StringBuilder.Length + val.Length + 1);
StringBuilder.Append(val);
StringBuilder.Append(' ');
}
This makes it 3n + 1. It is a rough estimate as StringBuilder allocates strings as it runs out of space - but if you EnsureCapacity you will prevent it from getting it wrong.
Probably the only way to be sure about how this is compiled is to build it and decompile it again with Refactor to see how it's internally handled. Anyway have in mind that probably it does not have impact on the whole app performance.
I have a string representation exactly like 'ComputerName -- IPAddress'; i.e:
'samarena -- 192.168.1.97'
. I want to get only the 'ComputerName' part from the actual representation by removing other characters. I'm actually quite beginner in using string.FormatMethods() .
Please help me out.
Thanks.
This should do it:
string test = "samarena -- 192.168.1.97";
var result = test.Split(new string[] { "--" }, StringSplitOptions.None)[0].Trim();
Result will equal samarena
you could split the string on ' -- ' and then use the first part
This should do it.
var yourString = "samarena -- 192.168.1.97";
var indexOfDash = yourString.IndexOf("-");
var yourComputerName = yourString.SubString(0, indexOfDash).Trim();
But the other answers using Trim are better :)
This'd be the totally imperative way.
If You are sure there is always a substring " -- " after the part You want, You can do this
myString.Substring(0, myString.IndexOf(" -- "))
Or use a shorter part of " -- ".
Try this:
char [] chars = {'-'};
string test = "samarena -- 192.168.1.97";
//computerName array will have the Computer Name at the very first index (it is a zero based index
string[] computerName = test.Split(chars,StringSplitOptions.RemoveEmptyEntries);
//computerName[0] is your computerName