Here is the code and it is working fine for a single input string
string[] stop_word = new string[]
{
"please",
"try",
"something",
"asking",
"-",
"(", ")",
"/",
".",
"was",
"the"
};
string str = "Please try something (by) yourself. -befor/e asking";
foreach (string word in stop_word)
{
str = str.ToLower().Replace(word, "").Trim();
}
and the output is by yourself before
and now I want to have
string str[] = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
and also may be the number of strings is greater than 2 then how to alter this above code to display the str array or store in a text file or database.
Please help with acknowledgements. Thanks
The code for single string need to be put inside a loop for string array
List<string> result = new List<string>();
for(int i =0; i<str.Length; i++)
{
foreach (string word in stop_word)
{
str[i] = str[i].ToLower().Replace(word, "").Trim();
str[i] = Regex.Replace(str[i], #"\s+", " ");
}
result.Add(str[i]);
}
foreach(string r in result)
{
//this is to printout the result
Console.WriteLine(r);
}
You can try it here: https://dotnetfiddle.net/wg83gM
EDIT:
Use regex to replace multiple spaces with one single space
Here is an easy to understand way to do it:
List<string> list = new List<string>();
foreach (string text in str)//loops through your str array
{
string newText =text;
foreach (string word in stop_word) //loops through your word array
{
newText = newText.ToLower().Replace(word, "").Trim();
}
list.Add(newText); //store the results in a list
}
Here is a working Demo
Does this work as you expect?
var results =
str
.Select(x => stop_word.Aggregate(x, (a, y) => a.ToLower().Replace(y, "").Trim()))
.ToArray();
I used this input:
string[] str = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
string[] stop_word = new string[]
{
"please", "try", "something", "asking", "-", "(", ")", "/", ".", "was", "the"
};
I got this output:
by yourself before cad
cover, adopted accuracy of change map
You can use Select() for this.
var results = str.Select(x => {
foreach (string word in stop_word)
{
x = x.ToLower().Replace(word, "").Trim();
}
return x;
}).ToList(); // You can use ToArray() if you wish too.
...
foreach(string result in results)
{
Console.WriteLine(result);
}
Result:
by yourself before cad
cover, adopted accuracy of change map
Related
I have a string array with values
patrick
portland
vic
and I want to achieve the following:
for the first pass I want to have an array with * appended to the end of each entry:
patrick*
portland*
vic*
for second pass, I want to replace * with a ~:
patrick*
portland*
vic~
patrick*
portland~
vic*
patrick~
portland*
vic*
for third pass, I want to replace another * with ~:
patrick~
portland*
vic~
patrick~
portland~
vic*
patrick*
portland~
vic~
and so on until all the * are replaced by ~.
Is there a way do it without recursion?
Edit 1:
Need the following strings generated based on: patrick portland vic
patrick*portland*vic*
patrick*portland*vic~
patrick*portland~vic*
patrick~portland*vic*
patrick~portland*vic~
patrick~portland~vic*
patrick*portland~vic~
patrick~portland~vic~
I thought it would be easier to split the string into an array and then work on.
Edit 2:
Managed to solve this using cartesian product.
string[] stnameSplit = streetName.Split(' ');
string[] chars = { "*", "~" };
var cartesianProduct = from name in stnameSplit
from cha in chars
select new { name, cha };
List<string> vals = cartesianProduct.Select(p => p.name + p.cha).ToList();
List<List<string>> embeddedList = new List<List<string>>();
int ctr = 0;
List<string> l = new List<string>();
foreach (string s in vals)
{
l.Add(s);
if (ctr % 2 == 1)
{
embeddedList.Add(l);
l = new List<string>();
}
ctr++;
}
var result = embeddedList.ToArray().CartesianProduct();
The last line calls the method CartesianProduct as described by Eric Lippert.
Thanks everyone for the help and guiding me in the right direction.
Given the solution that you posted in your question I thought it seemed a bit verbose. I thought I'd try to shorten.
Here it is:
string streetName = "patrick portland vic";
string[] split = streetName.Split(' ');
string[] chars = { "*", "~" };
IEnumerable<IEnumerable<string>> choices = split.Select(n => chars.Select(c => $"{n}{c}"));
IEnumerable<IEnumerable<string>> result = choices.CartesianProduct();
I have a column based txt file. How can I read any specific column programmatically?
So far I came up with this solution where it reads the specified column index for example: firstValue[0] will read all the (1) in the text file.
If I write it like this then I'll be able to read the first three index fine, but there has to be a cleaner approach.
Console.WriteLine(string.Join("", firstValue[0], firstValue1, firstValue[2], firstValue[3]));
If there was a way I could count the columns in the text file than pick the index of the column I want to read; that would be ideal.
I would like to read:
121
122
123
124
I've searched online for a similar problem, but they didn't quite have what I wanted.
string[] lines = File.ReadAllLines(YourFile);
foreach (var line in lines)
{
var firstValue = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(firstValue[0]);
//Console.WriteLine(string.Join("", firstValue[0], firstValue[1], firstValue[2], firstValue[3]));
}
Console.ReadKey();
You can try this one:
public static List<string> GetColumnValues(string[] lines, int columnNumber)
{
var result = new List<string>();
Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
foreach (var line in lines)
{
var cleanedLine = regex.Replace(line, " ");
var columns = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
result.Add(columns[columnNumber-1]);
}
return result;
}
Additional checks should be added, but you can get an idea.
The problem was, splitting it like like this:
var firstValue = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
firstValue would equal a concatenated string something like this 121 20412 010 in the foreach loop
So then I tried another approach which was:
var firstValue = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
Which indexed the columns, so I can choose which column I want the data to come from.
foreach (var line in lines)
{
var firstValue = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(firstValue[2]);
}
Output:
010
020
030
040
I have a string:
string data =
"item1 actived
item2 none
item special I none
item special II actived"
you can see 4 rows in the data.
I need to split a string into a List item as below:
item[0]={Name=item1, Status=actived}
item[1]={Name=item2, Status=none}
item[2]={Name=item Special I, Status=none}
item[3]={Name=item Special II, Status=actived}
I'm tried:
var s = SplitReturn(data);
public string[] SplitReturn(string name)
{
return name.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
How do I can Split space in my string and then convert to List?
string data =
#"item1 actived
item2 none
item special I none
item special II actived";
var result = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => {
int lastSpace = item.LastIndexOf(' ');
return new
{
Name = item.Substring(0, lastSpace).Trim(),
Status = item.Substring(lastSpace, item.Length - lastSpace).Trim()
}; }).ToList();
I have a text file containing many lines which look like this:
Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}
I know how to read lines from a file, but what's the best way to split and store the categories and their subitems in a dictionary afterwards? Let's say from a string array which contains all the above lines?
The idea to use a regexp is right, but I prefer using named captures for readability
var regexp = new Regex(#"(?<category>\w+?)\{(?<entities>.*?)\}");
var d = new Dictionary<string, List<string>>();
// you would replace this list with the lines read from the file
var list = new string[] {"Flowers{Tulip|Sun Flower|Rose}"
, " Gender{Female|Male}"
, "Pets{Cat|Dog|Rabbit}"};
foreach (var entry in list)
{
var mc = regexp.Matches(entry);
foreach (Match m in mc)
{
d.Add(m.Groups["category"].Value
, m.Groups["entities"].Value.Split('|').ToList());
}
}
You get a dictionary with the category as a key, and the values in a list of strings
you can use the Key and value on this code
string T = #"Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}";
foreach (var line in T.Split('\n'))//or while(!file.EndOfFile)
{
var S = line.Split(new char[] { '{', '|','}' }, StringSplitOptions.RemoveEmptyEntries);
string Key = S[0];
MessageBox.Show(Key);//sth like this
for (int i = 1 ; i < S.Length; i++)
{
string value = S[i];
MessageBox.Show(value);//sth like this
}
}
you can use this:
string line = reader.ReadLine();
Regex r = new Regex(#"(\w+){(\w+)}");
now loop the results of this regex:
foreach(Match m in r.Matches(line)) {
yourDict.Add(m.Groups[1], m.Groups[2].Split(' '));
}
What I'm trying to do is type in random words into box1, click a button and then print all the words that start with "D" in box2. So if I was to type in something like "Carrots Doors Apples Desks Dogs Carpet" and click the button "Doors Desks Dogs" would print in box2.
string s = box1.Text;
int i = s.IndexOf("D");
string e = s.Substring(i);
box2.Text = (e);
when I use this^^
It would print out "Doors Apples Desks Dogs Carpet" instead of just the D's.
NOTE: These words are an example, I could type anything into box1.
Any help?
You could simplify this by using LINQ
var allDWords = box1.Text.Split(' ').Where(w => w.StartsWith("D"));
box2.Text = String.Join(" ", allDWords);
Try this
box2.Text = String.Join(" ",
box1.Text.Split(' ')
.Where(p => p.StartsWith("D")));
You can match the D words with a regular expression and iterate over the results
Try this regex
D\w+
First you need to split up the text into words and then check to see if each word starts with D. When looking for the first character it's easier to just check it directly.
string s = box1.Text;
StringBuilder builder = new StringBuilder();
foreach (var cur in s.Split(new char[] { ' ' })) {
if (cur.Length > 0 && cur[0] == 'D') {
builder.Append(cur);
builder.Append(' ');
}
}
box2.Text = builder.ToString();
One thing you could do is:
Lets suppose,
string str = "Dog Cat Man etc";
string[] words = str.Split(' ');
List<string> wordStartWithD = new List<string>();
foreach (string strTemp in words)
if (strTemp.StartsWith("D"))
wordStartWithD.Add(strTemp);
Hope this help.