Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to add numbers in string  RSS feed

 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I am a newbie to Java. I have a string e.g "12 03". I need to add the two numbers present in

this string (sum = 15). Can someone please guide me how to do this.


Thanks in advance,
Sanjul
 
rahul V kumar
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could I know how your string is formed in that fashion ("12 3")?

Do some reading on String Tokenizer.

I am sure that you will find out how do to it yourself.

Hope this helps.

Follow this link
http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
[ October 22, 2004: Message edited by: rahul V kumar ]
 
Amit Saini
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use stringtokenizer to break up the token using " " as the delimiter.
Once you have done that, use Integer.parseInt to convert each of the strings to int and then add them. Easy.
 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a ton!


I need to change string "7777" to integer 7777, and integer 15 to string "15".

I would appreciate if you can help.

Thanks in advance,
Sanjul
 
rahul V kumar
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should get your answers here
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

String to int
int i = Integer.parseInt("7777");

you can have it in a try catch block or check to make sure that the string is indeed a valid number.
[ October 22, 2004: Message edited by: rahul V kumar ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!