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.
Related
How to count 2 or 3 letter words of a string using asp csharp, eg.
string value="This is my string value";
and output should look like this
2 letter words = 2
3 letter words = 0
4 letter words = 1
Please help, Thanks in advance.
You can try something like this:
split sentence by space to get array of words
group them by length of word (and order by that length)
iterate through every group and write letter count and number of words with that letter count
code
using System.Linq;
using System.Diagnostics;
...
var words = value.Split(' ');
var groupedByLength = words.GroupBy(w => w.Length).OrderBy(x => x.Key);
foreach (var grp in groupedByLength)
{
Debug.WriteLine(string.Format("{0} letter words: {1}", grp.Key, grp.Count()));
}
First of all you need to decide what counts as a word. A naive approach is to split the string with spaces, but this will also count commas. Another approach is to use the following regex
\b\w+?\b
and collect all the matches.
Now you got all the words in a words array, we can write a LINQ query:
var query = words.Where(x => x.Length >= 2 && x.Length <= 4)
.GroupBy(x => x.Length)
.Select(x => new { CharCount = x.Key, WordCount = x.Count() });
Then you can print the query out like this:
query.ToList().ForEach(Console.WriteLine);
This prints:
{ CharCount = 4, WordCount = 1 }
{ CharCount = 2, WordCount = 2 }
You can write some code yourself to produce a more formatted output.
If i understood your question correctly
You can do it using dictionary
First split the string by space in this case
string value = "This is my string value";
string[] words = value.Split(' ');
Then loop trough array of words and set the length of each word as a key of dictionary, note that I've used string as a key, but you can modify this to your needs.
Dictionary<string, int> latteWords = new Dictionary<string,int>();
for(int i=0;i<words.Length;i++)
{
string key = words[i].Length + " letter word";
if (latteWords.ContainsKey(key))
latteWords[key] += 1;
else
latteWords.Add(key, 1);
}
And the output would be
foreach(var ind in latteWords)
{
Console.WriteLine(ind.Key + " = " + ind.Value);
}
Modify this by wish.
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
I'd like to split a string using the Split function in the Regex class. The problem is that it removes the delimiters and I'd like to keep them. Preferably as separate elements in the splitee.
According to other discussions that I've found, there are only inconvenient ways to achieve that.
Any suggestions?
Just put the pattern into a capture-group, and the matches will also be included in the result.
string[] result = Regex.Split("123.456.789", #"(\.)");
Result:
{ "123", ".", "456", ".", "789" }
This also works for many other languages:
JavaScript: "123.456.789".split(/(\.)/g)
Python: re.split(r"(\.)", "123.456.789")
Perl: split(/(\.)/g, "123.456.789")
(Not Java though)
Use Matches to find the separators in the string, then get the values and the separators.
Example:
string input = "asdf,asdf;asdf.asdf,asdf,asdf";
var values = new List<string>();
int pos = 0;
foreach (Match m in Regex.Matches(input, "[,.;]")) {
values.Add(input.Substring(pos, m.Index - pos));
values.Add(m.Value);
pos = m.Index + m.Length;
}
values.Add(input.Substring(pos));
Say that input is "abc1defg2hi3jkl" and regex is to pick out digits.
String input = "abc1defg2hi3jkl";
var parts = Regex.Matches(input, #"\d+|\D+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
Parts would be: abc 1 defg 2 hi 3 jkl
For Java:
Arrays.stream("123.456.789".split("(?<=\\.)|(?=\\.)+"))
.forEach((p) -> {
System.out.println(p);
});
outputs:
123
.
456
.
789
inspired from this post (How to split string but keep delimiters in java?)
Add them back:
string[] Parts = "A,B,C,D,E".Split(',');
string[] Parts2 = new string[Parts.Length * 2 - 1];
for (int i = 0; i < Parts.Length; i++)
{
Parts2[i * 2] = Parts[i];
if (i < Parts.Length - 1)
Parts2[i * 2 + 1] = ",";
}
for c#:
Split paragraph to sentance keeping the delimiters
sentance is splited by . or ? or ! followed by one space (otherwise if there any mail id in sentance it will be splitted)
string data="first. second! third? ";
Regex delimiter = new Regex("(?<=[.?!] )"); //there is a space between ] and )
string[] afterRegex=delimiter.Split(data);
Result
first.
second!
third?
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!!
}