Click to See Complete Forum and Search --> : getting 2 words from a sentence
vivendi
November 23rd, 2009, 04:35 AM
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??
MNovy
November 23rd, 2009, 05:04 AM
This is easy.
Use the string split method (http://msdn.microsoft.com/en-us/library/system.string.split%28VS.71%29.aspx) 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.
foamy
November 24th, 2009, 07:07 AM
If you also want to eliminate punctuation I recommend this approach:
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();
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.