Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Splitting a string of asterisks

 
E Maton
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to split a string of asterisks (that will vary in length) with a space after every five asterisks. I have tried playing around w/ a for loop, string tokenizer, and regex and I haven't come up w/ the solution yet.
Yes, I am very new at studying Java! Any ideas?
 
Amit KumarS
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiiii,
your problem can be sorted out if you use following code as the last loop..

and few points i want you to note..
1. The following code will print one extra asterics than required

2. Your are using a lot of String mnipulation in loops.. which is not a good idea.. as it will create a lot of Strings in memory. you should use StringBuffer class instead. Eg: -

this is a more efficient way of doing String manipulation..
I think i am clear enough. If stil any queries please revert back..
Thanks
Amit
 
E Maton
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for taking the time to respond - it's much appreciated!
I corrected the code to output the correct number of asterisks:

For putting a space after every five there is still a problem: The code you gave me outputs 2 less asterisks than there should be (but the format of the asterisks is correct - something like: ***** ***** ***). I tried changing it to output correctly, but nothing has worked so far.
If I change the code to the following (either this or using StringBuffer) then the number of asterisks are correct but it outputs something like: * **** ***** ***
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try:
 
E Maton
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael and Joel -- both of your ideas worked!! Thanks to everyone for helping me learn more! I will research StringBuffers further so I will know to use them in the future. Here is the final result using both ideas:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic