How to search words starting with a particular char?

Discussion in 'Ruby' started by Toki Toki, May 2, 2008.

  1. Toki Toki

    Toki Toki Guest

    Hi to all!

    I need to search how many words are starting with a specific character
    in a text file, no problem to read the file, but after that I split it
    in words, how can
    I search all occurencies that's matching my criteria in the resulting
    array? Maybe split isn't the best solution?

    I would like an output similar to this:

    Number of words starting with ' ' = 12345

    Here's the code:

    txt = File.read("C:\\text.txt")

    list = txt.split

    Thanks.

    Best regards.
    --
    Posted via http://www.ruby-forum.com/.
    Toki Toki, May 2, 2008
    #1
    1. Advertising

  2. Toki Toki

    ThoML Guest

    > I need to search how many words are starting with a specific character

    A word border can be matched with \b.

    Using split + grep:
    irb(main)> a = 'foo bar foo bar foo bar'
    irb(main)> a.split(/\b/).grep(/^f\w*/)
    => ["foo", "foo", "foo"]
    irb(main)> a.split(/\b/).grep(/^f\w*/).size
    => 3

    Another solution would be to use scan:
    irb(main)> a.scan(/\bf\w*/)
    => ["foo", "foo", "foo"]
    irb(main)> a.scan(/\bf\w*/).size
    => 3
    ThoML, May 2, 2008
    #2
    1. Advertising

  3. Toki Toki

    Toki Toki Guest

    ThoML wrote:
    >> I need to search how many words are starting with a specific character

    >
    > A word border can be matched with \b.
    >
    > Using split + grep:
    > irb(main)> a = 'foo bar foo bar foo bar'
    > irb(main)> a.split(/\b/).grep(/^f\w*/)
    > => ["foo", "foo", "foo"]
    > irb(main)> a.split(/\b/).grep(/^f\w*/).size
    > => 3
    >
    > Another solution would be to use scan:
    > irb(main)> a.scan(/\bf\w*/)
    > => ["foo", "foo", "foo"]
    > irb(main)> a.scan(/\bf\w*/).size
    > => 3


    Thanks a lot for the helpful and fast answer.

    Best regards.

    --
    Posted via http://www.ruby-forum.com/.
    Toki Toki, May 2, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Strøiman
    Replies:
    1
    Views:
    2,070
    Peter Strøiman
    Aug 23, 2005
  2. Richard Heathfield
    Replies:
    7
    Views:
    350
    Barry Schwarz
    Oct 5, 2003
  3. lovecreatesbeauty
    Replies:
    1
    Views:
    1,012
    Ian Collins
    May 9, 2006
  4. utab

    Words Words

    utab, Feb 16, 2006, in forum: C++
    Replies:
    6
    Views:
    413
    Daniel T.
    Feb 16, 2006
  5. Dylan Nicholson
    Replies:
    6
    Views:
    365
    A. Sinan Unur
    Oct 19, 2007
Loading...

Share This Page