How to split by multiple strings in C# - c#

My Question consists of how might i split a string like this:
""List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2
\tdevice\r\n\r\n"
Into:
[n9887bc314,n12n1n2nj1jn2]
I have tried this but it throws the error "Argument 1: cannot convert from 'string' to 'char'"
string[] delimiterChars = new string[] {"\\","r","n","tdevice"};
string y = output.Substring(z+1);
string[] words;
words = y.Split(delimiterChars, StringSplitOptions.None);
I'm wondering if i'm doing something wrong because i'm quite new at c#.
Thanks A Lot

First of all String.Split accept strings[] as delimiters
Here is my code, hope it will helps:
string input = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiterChars = {
"\r\n",
"\tdevice",
"List of devices attached"
};
var words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
Console.WriteLine(word);
}

Split the whole string by the word device and then remove the tabs and new lines from them. Here is how:
var wholeString = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
var splits = wholeString.Split(new[] { "device" }, StringSplitOptions.RemoveEmptyEntries);
var device1 = splits[1].Substring(splits[1].IndexOf("\n") + 1).Replace("\t", "");
var device2 = splits[2].Substring(splits[2].IndexOf("\n") + 1).Replace("\t", "");

I've been doing a first aproach and it works, it might help:
I splited the input looking for "/tdevice" and then cleaned everyting before /r/n including the /r/n itself. It did the job and should work with your adb output.
EDIT:
I've refactored my answer to consider #LANimal answer (split using all delimiters) and I tried this code and works. (note the # usage)
static void Main(string[] args)
{
var inputString = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiters = {
#"\r\n",
#"\tdevice",
#"List of devices attached"
};
var chunks = inputString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = "[";
for (int i = 0; i < chunks.Length; i++)
{
result += chunks[i] + ",";
}
result = result.Remove(result.Length - 1);
result += "]";
Console.WriteLine(result);
Console.ReadLine();
}
I hope it helps,
Juan

You could do:
string str = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] lines = str.Split(new[] { #"\r\n" }, StringSplitOptions.None);
string firstDevice = lines[1].Replace(#"\tdevice", "");
string secondDevice = lines[2].Replace(#"\tdevice", "");

Related

Split string and keep delimiter in sequence [duplicate]

This question already exists:
C# split string but keep split chars / separators [duplicate]
Closed 4 years ago.
Is there a clever way to do the following string manipulation in C#?
I have any kind of string and im looking for a specified delimiter. The code should divide the string in words before and after delimiter and also include the delimiter. The delimiter could be several times in a row and also could be in the start or the end.
// PSEUDO CODE
string = "Hello****wide****world";
delimiter = "****";
// result should be a list<string> like
{"Hello","****","wide","****","world"}
You can try to use Regex and the pattern is (\*{4}).
string data = "Hello****wide****world";
string[] words = Regex.Split(data, #"(\*{4})");
List<string> result = words.ToList();
NOTE
* is a keyword in regex string, so you need to use \ to escape it.
c# online
i'll say split the string with the delimiter, then when creating the result add the delimiter after each item in the array.
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
List<string> result = new List<string>();
foreach(var item in listOfWords){
result.Add(item);
result.Add(delimiter);
}
return result;
You can do it like this. In the end, you can iterate over the result.
string input = "Hello****wide****world";
string delimiter = "****";
var listOfWords = input.Split(new string[] { delimiter }, StringSplitOptions.None);
List<string> result = new List<string>();
foreach (var item in listOfWords)
{
if (!item.Equals(listOfWords.Last()))
{
result.Add(item);
result.Add(delimiter);
}
else
{
result.Add(item);
}
}
untested
string[] words = Regex.Split(originalString, #"(?=****)");
List<string> wordsLst = words.ToList();
User Regex to do it :
string input = "Hello****wide****world";
string pattern = "(****)";
string[] substrings = Regex.Split(input, pattern);
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
StringBuilder result = new StringBuilder("");
result.Append("{");
foreach(var item in listOfWords){
if (!item.Equals(listOfWords.Last()))
{
result.Append($"\"{item}\",\"{delimiter}\",");
}
else
{
result.Append($"\"{item}\"");
}
}
result.Append("}");
var stringResult=result.ToString();

Extract contents between specific tags in a textfile - C#

I have a text file with the following information:
ALLOC
apple1
orange1
banana1
ALLOC
apple2
orange2
banana2
ALLOC
apple3
orange3
banana3
Based on the help from stackflow community, I am now able to read the whole file.I also found out that to extract contents between a tag, for ex, ALLOC, I could write:
var filelocation = #"c:\Fruits.txt";
var sectionLines = File.ReadAllLines(filelocation).TakeWhile(l => !l.StartsWith("ALLOC"));
But this will give me IEnumerable<string>:
apple1
orange1
banana1
apple2
orange2
banana2
apple3
orange3
How do I create 3 separate strings as
string1 = apple1 orange1 banana1
string2 = apple2 ornage2 banana2
string3 = apple3 orange3
In short, need to extract contents between tags.
Here is some approach how you can return result which you want:
string[] words = { "ALLOC", "apple1", "orange1", "banana1", "ALLOC", "apple2", "orange2", "banana2", "ALLOC" };
var result = string.Join(" ", words)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
First I am making single string of all words. Than I am splitting by "ALLOC", and selecting trimmed strings.
Result is:
string[] result = { "apple1 orange1 banana1", "apple2 orange2 banana2" };
For your case,
var filelocation = #"c:\Fruits.txt";
var allLines = File.ReadAllLines(filelocation);
var sectionLines = string.Join(" ", allLines)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
This might do the trick for you
string fullstr = File.ReadAllText("c:\\Fruits.txt");
string[] parts = fullstr.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries);
List<string> outputstr = new List<string>();
foreach(string p in parts)
{
outputstr.Add(p.Replace("\r\n", " ").Trim(' '));
}
Here we read all text at once using File.ReadAllText and then splitted it with ALLOC and then in the outputstr just added the splitted string by replacing \r\n that is new line with a space and trimmed the result.

Reading individual words into an array using streamreader C#

I am trying to get a list of words (below) to be put into an array. I want each word to be in it's own index.
Here is my code that I have so far.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(' ');
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Here is the list of words I want to import.
label
invoice
post
document
postal
calculations
copy
fedex
statement
financial
dhl
usps
8
notification
n
irs
ups
no
delivery
ticket
If someone could give me an example of how to get this to work, that would be a huge help.
Simplified code:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string[] badWords = File.ReadAllLines(badWordsFilePath);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
If every word starts on a new line then you do not need to create a for loop. The Split method will convert to an array for you.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWords = line.Split('\n');
You are splitting on space, but there is a newline between each word. Split on newline instead:
string[] badWordsLine = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Then you have to create the array to put the words in:
badWords = new string[badWordsLine.Length];
However, to loop through a string array just to copy the strings to a string array seems pointless. Just assing the string array to the variable. Also, you forgot to close the stream reader, which is best taken care of with a using block:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string line;
using (StreamReader sr = new StreamReader(badWordsFilePath)) {}
line = sr.ReadToEnd();
}
badWords = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Maybe try this modification? It allows on splitting on various white spaces.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(new string[] {" ", "\t", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Do you have to use a StreamReader? If you do not have to, then this code is clearer (in my opinion).
string text = File.ReadAllText(badWordsFilePath);
string[] words = Regex.Split(text, #"\s+");
If you're 100% certain that each word is on its own line and there are no empty lines, this might be overkill; and the File.ReadAllLines suggestion by #Ulugbek Umirov is simpler.

How to split a string and store in different string array

if i have a string like
string hello="HelloworldHellofriendsHelloPeople";
i would like to store this in a string like this
Helloworld
Hellofriends
HelloPeople
It has to change the line when it finds the string "hello"
thanks
string hello = "HelloworldHellofriendsHelloPeople";
var a = hello.Split(new string[] { "Hello"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in a)
Console.WriteLine("Hello" + s);
var result = hello.Split(new[] { "Hello" },
StringSplitOptions.RemoveEmptyEntries)
.Select(s => "Hello" + s);
You can use this regex
(?=Hello)
and then split the string using regex's split method!
Your code would be:
String matchpattern = #"(?=Hello)";
Regex re = new Regex(matchpattern);
String[] splitarray = re.Split(sourcestring);
You can use this code - based on string.Replace
var replace = hello.Replace( "Hello", "-Hello" );
var result = replace.Split("-");
You could use string.split to split on the word "Hello", and then append "Hello" back onto the string.
string[] helloArray = string.split("Hello");
foreach(string hello in helloArray)
{
hello = "Hello" + hello;
}
That will give the output you want of
Helloworld
Hellofriends
HelloPeople

How do I split a string into an array?

I want to split a string into an array. The string is as follows:
:hello:mr.zoghal:
I would like to split it as follows:
hello mr.zoghal
I tried ...
string[] split = string.Split(new Char[] {':'});
and now I want to have:
string something = hello ;
string something1 = mr.zoghal;
How can I accomplish this?
String myString = ":hello:mr.zoghal:";
string[] split = myString.Split(':');
string newString = string.Empty;
foreach(String s in split) {
newString += "something = " + s + "; ";
}
Your output would be:
something = hello; something = mr.zoghal;
For your original request:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
var somethings = split.Select(s => String.Format("something = {0};", s));
Console.WriteLine(String.Join("\n", somethings.ToArray()));
This will produce
something = hello;
something = mr.zoghal;
in accordance to your request.
Also, the line
string[] split = string.Split(new Char[] {':'});
is not legal C#. String.Split is an instance-level method whereas your current code is either trying to invoke Split on an instance named string (not legal as "string" is a reserved keyword) or is trying to invoke a static method named Split on the class String (there is no such method).
Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
string something = split[0];
string something1 = split[1];
Now you will have
something == "hello"
and
something1 == "mr.zoghal"
both evaluate as true. Is this what you are looking for?
It is much easier than that. There is already an option.
string mystring = ":hello:mr.zoghal:";
string[] split = mystring.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);

Categories

Resources