![]() |
Method not recognizing PAREN when looping through character array
Can anyone take a look at the code below? I have this method that is
supposed to return a string with only the first character of a word uppercase. This is working fine except for a string with parens in it. public class paren { public static String s = "STRING THAT (HAS PARENS) INSIDE OF IT."; public paren() { System.out.println("Before UCW: " + s); System.out.println(" After UCW: " + this.ucwords(s)); } public String ucwords(String str) { char[] broken = str.toLowerCase().toCharArray(); StringBuffer buf = new StringBuffer(); boolean doUpperCase = true; for (int i = 0; i < broken.length; i++) { if (doUpperCase) { buf.append(String.valueOf(broken[i]).toUpperCase()); doUpperCase = false; } else { //if (broken[i] == '(') <-- this doesn't work if (String.valueOf(broken[i]).equals("(")) // <-- doesn't work either doUpperCase = true; else if (broken[i] == ' ') doUpperCase = true; buf.append(broken[i]); } } return buf.toString(); } public static void main(String[] args) { new paren(); } } Any ideas on what I might be doing wrong? Cheers, Curts |
Re: Method not recognizing PAREN when looping through character array
Curts wrote:
> > Can anyone take a look at the code below? I have this method that is > supposed to return a string with only the first character of a word > uppercase. This is working fine except for a string with parens in > it. > > public class paren { > > public static String s = "STRING THAT (HAS PARENS) INSIDE OF IT."; > > public paren() { > System.out.println("Before UCW: " + s); > System.out.println(" After UCW: " + this.ucwords(s)); > } > > public String ucwords(String str) { > char[] broken = str.toLowerCase().toCharArray(); > StringBuffer buf = new StringBuffer(); > > boolean doUpperCase = true; > > for (int i = 0; i < broken.length; i++) { > > if (doUpperCase) { > buf.append(String.valueOf(broken[i]).toUpperCase()); > doUpperCase = false; > } else { > > //if (broken[i] == '(') <-- this doesn't work > if (String.valueOf(broken[i]).equals("(")) // <-- > doesn't work either > doUpperCase = true; > else if (broken[i] == ' ') > doUpperCase = true; > buf.append(broken[i]); > } > } > > return buf.toString(); > } > > public static void main(String[] args) { > new paren(); > } > } > > Any ideas on what I might be doing wrong? Sure, you shouldn't be checking the doUpperCase flag before you check for '(' or ' '. The space before the left parenthesis in the text sets doUpperCase to true, so you do a toUpperCase() on the parenthesis. Your algorithm is not very general. Homework? -- Lee Fesperman, FirstSQL, Inc. (http://www.firstsql.com) ================================================== ============ * The Ultimate DBMS is here! * FirstSQL/J Object/Relational DBMS (http://www.firstsql.com) |
| All times are GMT. The time now is 06:52 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.