dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: getting 2 words from a sentence

  1. #1
    Join Date
    Nov 2005
    Posts
    102

    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??

  2. #2
    Join Date
    Jul 2008
    Location
    Germany
    Posts
    210

    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.

  3. #3
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)