Results 1 to 4 of 4
  1. #1
    jimmy-lin is offline Member
    Join Date
    Oct 2009
    Posts
    17
    Rep Power
    0

    Default Replacing char in string help

    This is what I was given to codes

    Java Code:
        /**
         *  Write the function countCode.
         *  
         *  @param str the string to process.
         *  @return the number of times co?e appears in the string.
         *  
         *  Return the number of times that the string "code" 
         *  appears anywhere in the given string, except we'll 
         *  accept any letter for the 'd', so "cope" and "cooe" 
         *  count.
         *
         *  Some examples:
         *      countCode("aaacodebbb") returns 1
         *      countCode("codexxcode") returns 2
         *      countCode("cozexxcope") returns 2
         */
    Here is my codes:
    Java Code:
        public int countCode(String str)
        {
            int result = 0;
    
            int len = str.length() - 3;
            for (int i = 0; i < len; i++)
            {
            String word = str.substring(i, i + 4);
            if (word.equals("code"))        
            result = result + 1;
            }
            return result;
        }
    My question is how, do you code it so you can replace charAt('d') to any alphabetic letters.

  2. #2
    mrmatt1111's Avatar
    mrmatt1111 is offline Senior Member
    Join Date
    Aug 2009
    Location
    San Jose, CA, USA
    Posts
    320
    Rep Power
    6

    Default

    Because i'm in an evil mood: =)

    Java Code:
    public int countCode(String str)
    {
       return (str.length()-str.replaceAll("co[a-z]e", "").length()) / 4;
    }
    My Hobby Project: LegacyClone

  3. #3
    jimmy-lin is offline Member
    Join Date
    Oct 2009
    Posts
    17
    Rep Power
    0

    Default

    cool, that the shorter version, and i just found out that all i need to do is replace

    Java Code:
     if (word.equals("code"))
    to

    Java Code:
     if (word.matches("co\\we"))

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. replacing backslashes in String Object
    By nishiz in forum Advanced Java
    Replies: 9
    Last Post: 12-02-2010, 12:31 AM
  2. Replacing the chars within a string.
    By Mayur in forum New To Java
    Replies: 2
    Last Post: 03-27-2009, 04:00 AM
  3. Help Replacing String
    By 7oclock in forum New To Java
    Replies: 5
    Last Post: 02-14-2009, 07:31 AM
  4. char to string
    By kian_hong2000 in forum New To Java
    Replies: 2
    Last Post: 08-25-2008, 01:51 PM
  5. splitting string and replacing
    By itsme in forum New To Java
    Replies: 1
    Last Post: 12-11-2007, 03:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •