i am listbox to store different strings which user gives as input.
but i want to split those listbox items where i want to have the first word of every item as seperate string and rest as other string.
i am iterating the listbox item as
foreach (ListItem item in lstboxColumnList.Items)
{
column_name = temp + "\" "+item+"\"";
temp = column_name + "," + Environment.NewLine;
}
how could i get the splitted string
Assuming firs word ends with a space, you can use something like below:
string firsWord = sentence.SubString(0, sentence.IndexOf(' '));
string remainingSentence = sentence.SubString(sentence.IndexOf(' '), sentence.Length);
I dont know your listbox item's format..
but I assumed that your listbox item have at least 2 word and separate by a space..
so, you can do the splitting using substring and index of..
string first = sentence.SubString(0, sentence.IndexOf(" "));
string second = sentence.SubString(sentence.IndexOf(" ") + 1);
public void Test()
{
List<string> source = new List<string> {
"key1 some data",
"key2 some more data",
"key3 yada..."};
Dictionary<string, string> resultDictionary = source.ToDictionary(n => n.Split(' ').First, n => n.Substring(n.IndexOf(' ')));
List<string> resultStrings = source.Select(n => string.Format("\"{0}\",{1}", n.Split(' ').First, n.Substring(n.IndexOf(' ')))).ToList;
}
resultDictionary is a dictionary with the key set to the first word of each string in the source list.
The second closer matches the requirements in your question that it outputs a list of strings in the format you specified.
EDIT: Apologies, posted in VB first time round.
checkout:
var parts = lstboxColumnList.Items.OfType<ListItem>().Select(i => new {
Part1 = i.Text.Split(' ').FirstOrDefault(),
Part2 = i.Text.Substring(i.Text.IndexOf(' '))
});
foreach (var part in parts)
{
var p1 = part.Part1;
var p2 = part.Part2;
// TODO: use p1, p2 in magic code!!
}
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 list of value
list1[110,120,130]
I want to check in dictionary whether my dictionary table column value like
110_abc_ro
120_cfg_go
130_dfg_lo
110_abc_io
170_cfg_jo
is contained list value or not.
I want output like
110_abc_ro,110_abc_io is for list value 110
As I can't tell what your dictionary name/key-type is from the question, I came only as far as this. For every list-item (110, 120, etc.) you now iterate through the entries in your dictionary. Whenever a value from your dictionary contains the value you're iterating over from the list, it'll write it to a string, which you can then send/write/something else.
foreach (int i in list1)
{
string output = "";
foreach (KeyValuePair<var, string> kvp in yourDictionary)
{
if (kvp.Value.Contains(i.ToString()))
{
output += kvp.Value + ", ";
}
}
//print your outputstring here.
}
Edit:
you can use yourDictionary.Values.Select(x => x.Value.Contains(i.ToString())); instead of the foreach. Using a little from Lucifer's answer, you can turn it into the following;
foreach (int i in list1)
{
string output = String.Join(",", yourDictionary.Values.Select(x => x.Value.Contains(i.ToString())));
}
You can use String.Join() to join all values which match your list of int
As per MSDN this method Concatenates all the elements of a string collection, using the specified separator between each element.
eg:
string values = String.Join(",", yourDictionary.Where(x => list.Any(ele => x.Value.Contains(ele.ToString()))).Select(x => x.Value).ToList());
Try this:
string result= "";
list1.ForEach(item => {
yourDictionary.ToList().ForEach
(
pair =>
{
if (pair.Value.Contains(item.ToString()))
{
result = result + pair.Value + ", ";
}
}
);
});
Here you have simple solution:
int[] list1 = { 110, 120, 130 };
List<string> dict = new List<string> { "110_abc_ro", "120_cfg_go", "130_dfg_lo", "110_abc_io", "170_cfg_jo" };
for (int i = 0; i < list1.Length; i++)
{
string str = "Values from dictionary containing " + list1[i] + ":\n";
str += String.Concat(dict.Where(val => val.Contains(list1[i].ToString())).Select(val => val + ", "));
Console.Write(str);
}
I want to ignore the punctuation.So, I'm trying to make a program that counts all the appearences of every word in my text but without taking in consideration the punctuation marks.
So my program is:
static void Main(string[] args)
{
string text = "This my world. World, world,THIS WORLD ! Is this - the world .";
IDictionary<string, int> wordsCount =
new SortedDictionary<string, int>();
text=text.ToLower();
text = text.replaceAll("[^0-9a-zA-Z\text]", "X");
string[] words = text.Split(' ',',','-','!','.');
foreach (string word in words)
{
int count = 1;
if (wordsCount.ContainsKey(word))
count = wordsCount[word] + 1;
wordsCount[word] = count;
}
var items = from pair in wordsCount
orderby pair.Value ascending
select pair;
foreach (var p in items)
{
Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}
}
The output is:
is->1
my->1
the->1
this->3
world->5
(here is nothing) -> 8
How can I remove the punctuation here?
You should try specifying StringSplitOptions.RemoveEmptyEntries:
string[] words = text.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Note that instead of manually creating a char[] with all the punctuation characters, you may create a string and call ToCharArray() to get the array of characters.
I find it easier to read and to modify later on.
string[] words = text.Split(new char[]{' ',',','-','!','.'}, StringSplitOPtions.RemoveEmptyItems);
It is simple - first step is to remove undesired punctuation with function Replace and then continue with splitting as you have it.
... you can go with the making people cry version ...
"This my world. World, world,THIS WORLD ! Is this - the world ."
.ToLower()
.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.GroupBy(i => i)
.Select(i=>new{Word=i.Key, Count = i.Count()})
.OrderBy(k => k.Count)
.ToList()
.ForEach(Console.WriteLine);
.. output
{ Word = my, Count = 1 }
{ Word = is, Count = 1 }
{ Word = the, Count = 1 }
{ Word = this, Count = 3 }
{ Word = world, Count = 5 }
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
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.