File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

seeing id string has odd / even chars

 
dale con
Ranch Hand
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all

i can find the length of a string

String s = "mystringodd";

can someone show me how i can then see if the string conains an even number of characters

e.g String s contains 11 chars

whati want to do is see if String s is even, if not i need to append a 0 to make it even, so string s becomes this 0mystringodd

can anyone help me ou with this


many thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have the length, look at the % arithmetic operator. That will give you the remainder from a division which you can use to see if length is even or not. If you're still stuck, post some code and we'll go from there.
 
dale con
Ranch Hand
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks

i can get the remainder doing this

String s = "somestringvalue";

int n = s.length();

int remainder = n % 2;

but don't know how append String s with x number of 0's to make the String s even
 
Seb Mathe
Ranch Hand
Posts: 225
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if your length is odd, and then you add one char, your new length becomes even, no ?
[ October 18, 2005: Message edited by: Seb Mathe ]
 
Joel McNary
Bartender
Posts: 1824
Eclipse IDE Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you appending or prepending?

In either case, you have two basic choices: String concatenation or a StringBuffer.

String concatenation is simpler and, in this case, is more readable.


Note that Strings are immutable -- you can't change them, you can only create new strings based on them. (Of course, you can reassign a reference to point to a new String; you can say s = "0" + s;).

The StringBuffer alternative is best used when you are doing large blocks of concatenation.

[ October 18, 2005: Message edited by: Joel McNary ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic