简体   繁体   中英

String to Dictionary or Array in C#

I have a string as followed:

Charlie Sheen is Cool
BBBB
He likes to run
BBB
When does he run?
BBBB

He lives here
BBBB
?
[
I like Charlie Sheen
BBBB

I would like to separate the string into two different Arrays. One for the phrases on top of the B's and for the B's itself. Or even better, have a dictionary with the phrases as the key's and the B's as values. I would also like to ignore all empty lines and lines that do not start with a letter. How would I go about doing it?

string[] newText = file.Split(new string[] { "\n", "\r\n",},StringSplitOptions.RemoveEmptyEntries);
int count = 0;
Regex symbol = new Regex("^[[]]$"); //these are the symbols I want to detect
Dictionary<string, string> patternedText = new Dictionary<string,string>();

foreach(string s in newText){
int bCount = 0;
count++;
bCount++; //position of where it detects a match
if(symbol.isMatch(s)){ 
newText[count-bCount] = s;
    }else{ newText[count] = s;
   patternedText.Add(newText[count],newText[count+1]);
}

Basically I want the format of the array to be:
Phrase with symbols
BBB
Phrase with symbols
BBBB
Phrase
BBB with symbols

And filter out all empty lines and the symbols on any line to be added to only the phrases.

Here's what you can do:

  1. split the string using '\\n' (new line feed), that will give you an array of all lines.
  2. Use a regular expression and/or a loop to do the cleaning (remove lines with only one symbol and the BBB in the succeeding line).
  3. Create a dictionary and iterate the array to put the (n)th element as the key and (n+1)th element as the value. (be careful of the boundary lines).

A loop is the sane and efficient approach, but if you're a LINQaholic:

var dictionary = file.Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
    .Select((line, index) => (line, index))
    .GroupBy(tuple => tuple.index / 2)
    .ToDictionary(group => group.First().line, group => group.Last().line);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM