|
-
November 23rd, 2009, 05:35 AM
#1
getting 2 words from a sentence
Hey, suppose i have the following sentence:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit."
Now i need to split this sentence into pieces of two words. So i need the following result:
Lorem ipsum
ipsum dolor
dolor sit
sit amet
amet consectetur
consectetur adipiscing
adipiscing elit
But i'm not sure how to do this...?? Could anyone please help me out a bit with this??
-
November 23rd, 2009, 06:04 AM
#2
Re: getting 2 words from a sentence
This is easy.
Use the string split method to put whole sentence into single words in an array,
then just go through the array in 2-steps and pick up your words and use them as you like.
-
November 24th, 2009, 08:07 AM
#3
Re: getting 2 words from a sentence
If you also want to eliminate punctuation I recommend this approach:
Code:
try
{
string input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
string[] words = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
string output = "";
for(int i = 0; i < words.Length; i++)
{
if(i + 1 < words.Length)
{
string word = words[i] + " " + words[i+1];
string legalWords = "";
foreach(char c in word)
if(allowedChars.Contains(c.ToString()))
legalWords += c.ToString();
if(legalWords != "")
output += legalWords + Environment.NewLine;
}
}
Console.WriteLine(output);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadKey();
}
It's not a bug, it's a feature!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|