4 Replies - 365 Views - Last Post: 28 November 2011 - 07:46 PM Rate Topic: -----

#1 ked22  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-April 10

Getting the index of the + character in string using indexOf

Posted 28 November 2011 - 06:13 PM

Hi, I'm having a hard time getting a valid return value from indexOf(string) and indexOf(int char) when looking for the index of + in the string "0.5x + 3x". It should be 5 (if I can read right.. :sweatdrop: ) but it keeps returning 9 (the length of the string) no whether i use one overloaded function or the other... Can anybody please help me with that? Here's the code:


String step = "add 0.5x + 3x";

int index1 = step.indexOf(43);      //43 is the ascii code of +
or
step.indexOf("+");





Is This A Good Question/Topic? 0
  • +

Replies To: Getting the index of the + character in string using indexOf

#2 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: Getting the index of the + character in string using indexOf

Posted 28 November 2011 - 06:24 PM

From what I see the string is "add 0.5x + 3x", so index of + will be 9!!

From what I see the string is "add 0.5x + 3x", so index of + will be 9!!
Was This Post Helpful? 2
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Getting the index of the + character in string using indexOf

Posted 28 November 2011 - 07:00 PM

The method signature is String.indexOf(int ch)
so shoulb be
int x = step.indexOf('+'); // '+' not "+"
Was This Post Helpful? 0
  • +
  • -

#4 ked22  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-April 10

Re: Getting the index of the + character in string using indexOf

Posted 28 November 2011 - 07:13 PM

Wow, turns out I actually just wasnt't looking at the code well enough! I was wanting the position of the + in a substring of step which I use later in the program.. that's why the indexes didn't match. Reading your post helped me realize that smohd, thanks!
And pbl there is more than one version of the function, check the String reference! Thanks for help though!
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Getting the index of the + character in string using indexOf

Posted 28 November 2011 - 07:46 PM

Oups... my bad sorry
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1