Taking parts out of a string, how? - c#

So I have a server that receives a connection with the message being converted to a string, I then have this string split between by the spaces

So you have a line:
var line = "hello world my name is bob";
And you don't want "world" or "is", so you want:
"hello my name bob"
If you split to a list, remove the things you don't want and recombine to a line, you won't have extraneous spaces:
var list = line.Split().ToList();
list.Remove("world");
list.Remove("is");
var result = string.Join(" ", list);
Or if you know the exact index positions of your list items, you can use RemoveAt, but remove them in order from highest index to lowest, because if you e.g. want to remove 1 and 4, removing 1 first will mean that the 4 you wanted to remove is now in index 3.. Example:
var list = line.Split().ToList();
list.RemoveAt(4); //is
list.RemoveAt(1); //world
var result = string.Join(" ", list);
If you're seeking a behavior that is like string.Replace, which removes all occurrences, you can use RemoveAll:
var line = "hello is world is my is name is bob";
var list = line.Split().ToList();
list.RemoveAll(w => w == "is"); //every occurence of "is"
var result = string.Join(" ", list);

You could remove the empty space using TrimStart() method.
Something like this:
string text = "Hello World";
string[] textSplited = text.Split(' ');
string result = text.Replace(textSplited[0], "").TrimStart();

Assuming that you only want to remove the first word and not all repeats of it, a much more efficient way is to use the overload of split that lets you control the maximum number of splits (the argument is the maximum number of results, which is one more than the maximum number of splits):
string[] arguments = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); // split only once
User.data = arguments.Skip(1).FirstOrDefault();
arguments[1] does the right thing when there are "more" arguments, but throw IndexOutOfRangeException if the number of words is zero or one. That could be fixed without LINQ by (arguments.Length > 1)? arguments[1]: string.Empty

If you're just removing the first word of a string, you don't need to use Split at all; doing a Substring after you found the space will be more efficient.
var line = ...
var idx = line.IndexOf(' ')+1;
line = line.Substring(idx);
or in recent C# versions
line = line[idx..];

Related

How to take a string, split it into an array and then join it back together

I have some code that will take in a string from console in [0,0,0,0] format. I then want to split it into an array but leave the [] and only take the numbers. How do i do this? This is what i have, i thought i could split it all and remove the brackets after but it doesnt seem to take the brackets and rather just leaves a null space. is there a way to split from index 1 to -1?
input = Console.ReadLine();
Char[] splitChars = {'[',',',']'};
List<string> splitString = new List<string>(input.Split(splitChars));
Console.WriteLine("[" + String.Join(",", splitString) + "]");
Console.ReadKey();
I love using LinqPad for such tasks, because you can use Console.WriteLine() to get the details of a result like so:
It becomes obvious that you have empty entries, i.e. "" at the beginning and the end. You want to remove those with the overloaded funtion that takes StringSplitOptions.RemoveEmptyEntries [MSDN]:
List<string> splitString = new List<string>(input.Split(splitChars, StringSplitOptions.RemoveEmptyEntries));
Result:

How do I get quoted fields from a delimited string as a list of unquoted values using LINQ?

Original text line is:
"125"|"Bio Methyl"|"99991"|"OPT12"|"CB"|"1"|"12"|"5"|"23"
Expected string list is free of double quotes and split by |:
125
Bio Methyl
99991
The text may contain empty quoted strings as in (former "OPT12" value now empty ""):
"125"|"Bio Methyl"|"99991"|""|"CB"|"1"|"12"|"5"|"23"
So I checked these two questions & answers :QA1 and QA2 to derive my solution.
var eList = uEList.ElementAt(i).Split(BarDelimiter);
var xList = eList.ElementAt(0).Where(char.IsDigit).ToList();
Of course it doesn't work the way I need it to be since xList is a list with elements like this: xList(0) = 1, xList(1) = 2, xList(2) = 5
I do not want to write another line to join them because this doesn't look like a suitable solution. There has to be something better with LINQ right?
How about this:
// Based on OPs comment: preserve empty non-quoted entries.
var splitOptions = StringSplitOptions.None;
//change to the below if empty entries should be removed
//var splitOptions = StringSplitOptions.None;
var line = "\"125\"|\"Bio Methyl\"|\"99991\"|\"OPT12\"|\"CB\"|\"1\"|\"12\"|\"5\"|\"23\"";
var result = line
.Split(new[] { "|" }, splitOptions)
.Select(p => p.Trim('\"'))
.ToList();
Console.WriteLine(string.Join(", ", result));
The Split(...) statement splits the input into an array with parts like
{ \"99991\", \"OPT12\", ... };
The p.Trim('\"') statement removes the leading and trailing quote from each of the parts.
As an alternative to the trimming, if there's no " in your values, you could simply sanitize the input before splitting it. You can do so by replacing the " symbol by nothing (either "" or string.Empty).
Your Split code would then give the correct result afterwards:
string uEList = "\"125\"|\"Bio Methyl\"|\"99991\"|\"OPT12\"|\"CB\"|\"1\"|\"12\"|\"5\"|\"23\"";
var eList = uEList.Replace("\"", string.Empty).Split(BarDelimiter);

Shortcut for splitting only once in C#?

Okay, lets say I have a string:
string text = "one|two|three";
If I do string[] texts = text.Split('|'); I will end up with a string array of three objects. However, this isn't what I want. What I actually want is to split the string only once... so the two arrays I could would be this:
one
two|three
Additionally, is there a way to do a single split with the last occurrence in a string? So I get:
one|two
three
As well, is there a way to split by a string, instead of a character? So I could do Split("||")
Split method takes a count as parameter, you can pass 2 in that position, which basically says that you're interested in only 2 elements maximum. You'll get the expected result.
For second question: There is no built in way AFAIK. You may need to implement it yourself by splitting all and joining first and second back.
C#'s String.Split() can take a second argument that can define the number of elements to return:
string[] texts = text.Split(new char[] { '|' }, 2);
For your first scenario, you can pass a parameter of how many strings to split into.
var text = "one|two|three";
var result = text.Split(new char[] { '|' }, 2);
Your second scenario requires a little more magic.
var text = "one|two|three";
var list = text.Split('|');
var result = new string[] { string.Join("|", list, 0, list.Length - 1), list[list.Length - 1] };
Code has not been verified to check results before using.
Well, I took it as a challenge to do your second one in one line. The result is... not pretty, mostly because it's surprisingly difficult to reverse a string and keep it as a string.
string text = "one|two|three";
var result = new String(text.Reverse().ToArray()).Split(new char[] {'|'}, 2).Reverse().Select(c => new String(c.Reverse().ToArray()));
Basically, you reverse it, then follow the same procedure as the first one, then reverse each individual one, as well as the resulting array.
You can simply do like this as well...
//To split at first occurence of '|'
if(text.Containts('|')){
beginning = text.subString(0,text.IndexOf('|'));
ending = text.subString(text.IndexOf('|');
}
//To split at last occurence of '|'
if(text.Contains('|')){
beginning = text.subString(0,text.LastIndexOf('|'));
ending = text.subString(text.LastIndexOf('|');
}
Second question was fun. I solved it this way:
string text = "one|two|three";
var result =
new []
{
string.Concat(text.ToCharArray().TakeWhile((c, i) => i <= text.LastIndexOf("|"))),
string.Concat(text.ToCharArray().SkipWhile((c, i) => i <= text.LastIndexOf("|")))
};

Auto-numbering each line in textbox

I want to auto number each line that a user puts into a textbox and display the result in another textbox.
Turn this
blah blah blah
some stuff to be numbered
more stuff to number
to this
1 blah blah blah
2 some stuff to be numbered
3 more stuff to number
so far I have
output.Text = Regex.Replace(input.Text, input.Text, #"{1,}+");
But this is replacing all text with {1,}
I cant seem to figure out how to loop each line back after placing a number and a space.
(I am new to c#)
Any suggestions?
It might be simpler to implement a non-Regex solution:
var numberedLines = input.Text
.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select ((line, index) => (index + 1) + " " + line)
.ToArray();
var result = string.Join(Environment.NewLine, numberedLines);
output.Text = result;
The first line uses string.Split() to split up the string around line returns into an array. Then I use LINQ .Select method to apply a function to each element in the array - in this case, adding line number and space at the beginning of each line (index + 1 is necessary because the index values are 0-based). Then I use string.Join method to put the array back together into a single string.
Demo: http://ideone.com/DrFTfl
It can actually be done with a Regular Expression if you use a MatchEvaluator delegate to apply the line numbering:
var index = 1;
output.Text = Regex.Replace(input.Text, "^",
(Match m) => (index++).ToString() + " ",
RegexOptions.Multiline);
The pattern ^ typically matches the beginning of an expression. However, with RegexOptions.Multiline, it matches the beginning of each line. Then for replacement, I use a delegate (anonymous function) that adds # + space to the beginning of the line, and then increments the index counter for the next row.
Demo: http://ideone.com/9LD0ZY
Why not just split by \r\n, concatenate each line of the string[] with an incremented number and a space, and then join by \r\n ?
If you're new to C# lets keep it as simple as possible.
By the looks of it you already have all your strings. So it boils down to this:
// store all lines in a list
// ...
var list = new List<string> {"blah", "blah2", "and some more blah"};
var list2 = new List<string>();
var i = 1;
foreach (var str in list)
{
list2.Add(string.Format("{0} {1}", i, str));
i++;
}
// write contents of list2 back to wherever you want them visualized

How to parse the numbers from the text and display it in textBox? c#

I have a string with the following text:
:0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:
How do I parse the final number? i.e.:
194176015020283762507
You should first use String.Split() to separate the string by the colon (':') separators. Then access the correct element.
var input = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
var split = input.Split(':');
var final = split[3];
Note that by default, Split() keeps empty entries. You will have one at the beginning and end, because of the initial and ending colons. You could also use:
var split = input.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
var final = split[2];
which, as the option implies, removes empty entries from the array. So your number would be at index 2 instead of 3.
string str = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
string num = str.Split(':')[3];
var finalNumber = input.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)
.Last()
This code will split your input string into strings, separated by : (empty strings are removed from start and end of sequence). And last string is returned, which is your finalNumber.

Categories

Resources