Results 1 to 4 of 4
Thread: Replacing char in string help
- 10-12-2009, 04:26 AM #1
Member
- Join Date
- Oct 2009
- Posts
- 17
- Rep Power
- 0
Replacing char in string help
This is what I was given to codes
Here is my 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 */
My question is how, do you code it so you can replace charAt('d') to any alphabetic letters.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; }
- 10-12-2009, 05:19 AM #2
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
- 10-12-2009, 05:32 AM #3
Member
- Join Date
- Oct 2009
- Posts
- 17
- Rep Power
- 0
cool, that the shorter version, and i just found out that all i need to do is replace
toJava Code:if (word.equals("code"))
Java Code:if (word.matches("co\\we"))
-
I believe that if you use your regex with str.split(regex, -1) the length of the array returned will be of some interest.
Similar Threads
-
replacing backslashes in String Object
By nishiz in forum Advanced JavaReplies: 9Last Post: 12-02-2010, 12:31 AM -
Replacing the chars within a string.
By Mayur in forum New To JavaReplies: 2Last Post: 03-27-2009, 04:00 AM -
Help Replacing String
By 7oclock in forum New To JavaReplies: 5Last Post: 02-14-2009, 07:31 AM -
char to string
By kian_hong2000 in forum New To JavaReplies: 2Last Post: 08-25-2008, 01:51 PM -
splitting string and replacing
By itsme in forum New To JavaReplies: 1Last Post: 12-11-2007, 03:08 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks