c# split string - c#

I have this code that splits a specific string.
str = "\n\nThis\nString\nis\nsplit\ninto\narray";
string[] delimiterChar = { "\n" };
var splitArray = str.Split(delimiterChar);
The split array is simple array of strings, but why isn't it possible to remove the first 2 item by using:
splitArray[0].remove();
splitArray[0].remove();

If you need to remove empty entries, then just specify it in the split method. There is no need to remove them manually.
var splitArray = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries);
If you want to specifically remove certain specific elements, then you can convert the array (non-mutable) to a list (mutable), and work on it like:
var splitList = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries).ToList();
splitList.RemoveAt(0);

This might be one of the solution which might get the desired result.
string str = "\n\nThis\nString\nis\nsplit\ninto\narray";
str = str.TrimStart('\n');
var splitArray = str.Split('\n');

yes,but sometimes the string contains random string at the first 3 indexes..
so i want to split this simple string into Array via Split and remove .
The split array is simple array of strings, but why isn't it possible to remove the first 2 items
Split it and then skip whatever number of items you wish using Linq:
// I am skipping 3 for example
var splitArray = str.Split(delimiterChar).Skip(3).ToList();
Make sure to add this to the list of using statements:
using System.Linq;

Related

How to parse a text file and find a string between two other

For example, let's say I have this:
string test = "id:test THISISTHESTRINGIWANT id2:test"
And I want to get THISISTHESTRINGIWANT. In order to do that I was wondering if its possible to find it like this:
left_string = "id:test ", right_string = " id2"
Thank You
You can use the .split like this
string test = "id:test THISISTHESTRINGIWANT id2:test"
char[] delimiterChars = { ' '};
string[] output= test.Split(delimiterChars);
this will give you 3 strings {id:test,THISISTHESTRINGIWANT,id2:test}
you can then iterate through the string array with whatever condition you want to weed out the unwanted data or you can change the char array to include any characters you want to split on.

C# - Convert string, to a two dimensional string array

I can't seem to figure this out.
I want to convert this:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
To a two dimensional array (or list) so it looks like this:
fooBarArray[0] = Array['Foo', "bar"];
fooBarArray[1] = Array['Foo', "bar"];
fooBarArray[2] = Array['Foo', "bar"];
... etc.
I have tried spliting by ("],") and then cleaning the string and creating an array afterwards. But it's just to damn UGLY!
I want a cleaner version. Is there no method built in for such a method in C#?
// Thanks
Since your question is not giving us enough information I will assume that you are trying to convert some JSON into an array of strings.
As far as I know there is no build in method in C# for this.
You could use an extension for this. Newtonsoft JSON
After installing this package you will be able to use the following code:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(foobarString);
First, split it by "[[", "], [", "]]"
var array1 = foobarString.Split(new string[] {"[[", "], [", "]]"}, StringSplitOptions.RemoveEmptyEntries);
array1 will contain "'Foo', 'bar'", "'Foo', 'bar'", "'Foo', 'bar'"
Then you can split every element by ','
var fooBarArray = array1.Select(x => x.Split(',').ToArray()).ToArray()
You can do it in one line
var fooBarArray = foobarString.Split(new string[] { "[[", "], [", "]]" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(',').ToArray()).ToArray()
You could use Regex to get the array elements from your source string and then convert the matches into your arrays. Something like this should do the trick:
var input = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
// search for [' more than one word character, put them into group a ',
// more than one whitespace ' more than one word character, put them into group b ']
var arrayMatches = Regex.Matches(input, #"\['(?<a>[\w]+)',\s+'(?<b>[\w]+)'\]");
var arrays = new List<string[]>();
foreach (Match arrayMatch in arrayMatches)
{
// if the match was unsuccessful, take the next match
if(!arrayMatch.Success)
continue;
// create a new string array with element in group a as first element and the element in groub b as the second one
var array = new [] {arrayMatch.Groups["a"].Value, arrayMatch.Groups["b"].Value};
arrays.Add(array);
}
// convert list to array
return arrays.ToArray();
{
const string oldString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<string>>>(oldString);
}
There you can find some examples. The String.Split function returns an array so you can do
string[] lines = foobarString.Split(new char[]{']'}, StringSplitOptions.RemoveEmtpyEntries);
fooBarArray[0] = lines[i].Split(new char[]{'[',']', ','}, StringSplitOptions.RemoveEmtpyEntries);
Take a look at this thread: multidimensional-array-vs

Regex for Removing All the repetation of a string and assign to an array

I have the following text in a file:
"SHOP_ORDER001","SHOP_ORDER002","SHOP_ORDER003","SHOP_ORDER004","SHOP_ORDER005"
Now I am getting the values by reading the file and assigning to array by spilt:
String orderValue = "";
string[] orderArray;
orderValue = File.ReadAllText(#"C:\File.txt");
orderArray = orderValue.Split(',');
But I am getting the values as :
I need the Values in Array as "ORDER001","ORDER002","ORDER003"
The \" you see is just added by debugger visualizer for strings (because quote is a special characted and need to be escaped to don't get confused), don't worry they're not in your orderArray.
In case you want to remove quotes too so that your array will be:
SHOP_ORDER001
SHOP_ORDER002
...
Just use this (with LINQ):
var orderArray = orderValue.Split(',').Select(x => x.Trim('"'));
By the way String.Split isn't very robust unless you're sure each field will never contain a comma.
EDIT
To answer the point you added in the comments if you need to remove SHOP_ just write this:
var orderArray = orderValue.Split(',')
.Select(x => x.Trim('"').Substring("SHOP_".Length));
use this regex
var res = Regex.Matches(orderValue, #"(?<=""SHOP_)[^""]+?(?="")");
You could use this:
string[] result = Regex.Split(orderValue, "(?:^\"SHOP_)|(?:\",\"SHOP_)|(?:\"$)");
However you will have to skip the first and last items in the resulting array as they will always be empty strings.
Silly question but why don't you just do
.Replace("SHOP_", "");

split a string from a text file into another list

Hi i know the Title might sound a little confusing but im reading in a text file with many lines of data
Example
12345 Test
34567 Test2
i read in the text 1 line at a time and add to a list
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
}
}
how do i then separate the 1234 from the test so i can pull only the first column of data if i need like list(1).pars[1] would be 12345 and list(2).pars[2] would be test2
i know this sounds foggy but i hope someone out there understands
Maybe something like this:
string test="12345 Test";
var ls= test.Split(' ');
This will get you a array of string. You can get them with ls[0] and ls[1].
If you just what the 12345 then ls[0] is the one to choose.
If you're ok with having a list of string[]'s you can simply do this:
var list = new List<string[]>();
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line.Split(' '));
}
}
string firstWord = list[0][0]; //12345
string secondWord = list[0][1]; //Test
When you have a string of text you can use the Split() method to split it in many parts. If you're sure every word (separated by one or more spaces) is a column you can simply write:
string[] columns = line.Split(' ');
There are several overloads of that function, you can specify if blank fields are skipped (you may have, for example columns[1] empty in a line composed by 2 words but separated by two spaces). If you're sure about the number of columns you can fix that limit too (so if any text after the last column will be treated as a single field).
In your case (add to the list only the first column) you may write:
if (String.IsNullOrWhiteSpace(line))
continue;
string[] columns = line.TrimLeft().Split(new char[] { ' ' }, 2);
list.Add(columns[0]);
First check is to skip empty or lines composed just of spaces. The TrimLeft() is to remove spaces from beginning of the line (if any). The first column can't be empty (because the TrimLeft() so yo do not even need to use StringSplitOptions.RemoveEmptyEntries with an additional if (columns.Length > 1). Finally, if the file is small enough you can read it in memory with a single call to File.ReadAllLines() and simplify everything with a little of LINQ:
list.Add(
File.ReadAllLines("test.txt")
.Where(x => !String.IsNullOrWhiteSpace(x))
.Select(x => x.TrimLeft().Split(new char[] { ' ' }, 2)[0]));
Note that with the first parameter you can specify more than one valid separator.
When you have multiple spaces
Regex r = new Regex(" +");
string [] splitString = r.Split(stringWithMultipleSpaces);
var splitted = System.IO.File.ReadAllLines("Test.txt")
.Select(line => line.Split(' ')).ToArray();
var list1 = splitted.Select(split_line => split_line[0]).ToArray();
var list2 = splitted.Select(split_line => split_line[1]).ToArray();

Extracting values from a string in C#

I have the following string which i would like to retrieve some values from:
============================
Control 127232:
map #;-
============================
Control 127235:
map $;NULL
============================
Control 127236:
I want to take only the Control . Hence is there a way to retrieve from that string above into an array containing like [127232, 127235, 127236]?
One way of achieving this is with regular expressions, which does introduce some complexity but will give the answer you want with a little LINQ for good measure.
Start with a regular expression to capture, within a group, the data you want:
var regex = new Regex(#"Control\s+(\d+):");
This will look for the literal string "Control" followed by one or more whitespace characters, followed by one or more numbers (within a capture group) followed by a literal string ":".
Then capture matches from your input using the regular expression defined above:
var matches = regex.Matches(inputString);
Then, using a bit of LINQ you can turn this to an array
var arr = matches.OfType<Match>()
.Select(m => long.Parse(m.Groups[1].Value))
.ToArray();
now arr is an array of long's containing just the numbers.
Live example here: http://rextester.com/rundotnet?code=ZCMH97137
try this (assuming your string is named s and each line is made with \n):
List<string> ret = new List<string>();
foreach (string t in s.Split('\n').Where(p => p.StartsWith("Control")))
ret.Add(t.Replace("Control ", "").Replace(":", ""));
ret.Add(...) part is not elegant, but works...
EDITED:
If you want an array use string[] arr = ret.ToArray();
SYNOPSYS:
I see you're really a newbie, so I try to explain:
s.Split('\n') creates a string[] (every line in your string)
.Where(...) part extracts from the array only strings starting with Control
foreach part navigates through returned array taking one string at a time
t.Replace(..) cuts unwanted string out
ret.Add(...) finally adds searched items into returning list
Off the top of my head try this (it's quick and dirty), assuming the text you want to search is in the variable 'text':
List<string> numbers = System.Text.RegularExpressions.Regex.Split(text, "[^\\d+]").ToList();
numbers.RemoveAll(item => item == "");
The first line splits out all the numbers into separate items in a list, it also splits out lots of empty strings, the second line removes the empty strings leaving you with a list of the three numbers. if you want to convert that back to an array just add the following line to the end:
var numberArray = numbers.ToArray();
Yes, the way exists. I can't recall a simple way for It, but string is to be parsed for extracting this values. Algorithm of it is next:
Find a word "Control" in string and its end
Find a group of digits after the word
Extract number by int.parse or TryParse
If not the end of the string - goto to step one
realizing of this algorithm is almost primitive..)
This is simplest implementation (your string is str):
int i, number, index = 0;
while ((index = str.IndexOf(':', index)) != -1)
{
i = index - 1;
while (i >= 0 && char.IsDigit(str[i])) i--;
if (++i < index)
{
number = int.Parse(str.Substring(i, index - i));
Console.WriteLine("Number: " + number);
}
index ++;
}
Using LINQ for such a little operation is doubtful.

Categories