• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Text Formatting Question  RSS feed

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everyone,

I am writing a program that reads in sentences from a text file, and then converts those sentences (a StringBuffer) to a String. Then, I convert that String into a character array. Once I do that, I want to do the following...

Right now, the following code will insert a '^' at the MAXPOS (say, 25) position in the character array, IF that MAXPOS position is a blank space ' '. Each time MAXPOS is reached, the count will reset to 0 and will again search the array to MAXPOS...this happens until the end of the character array.

Here is what I cannot do, and was wondering if someone can help me...If the MAXPOS position is not a blank space, I want to insert a '^' to the nearest blank space BEFORE the MAXPOS occurs (So, the blank space before the current word).



Does anyone have any ideas? I'd greatly appreciate it. I'm not restricted to using a character array - analyzing the String directly is fine, too.

Thanks!
 
Marshal
Posts: 59765
188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both using a char[] array and using a String look as if they add unnecessary stages to your computation. You can do that directly on the StringBuffer. By the way: StringBuilder is likely to be more efficient.
Go through the StringBuilder class and you find all sorts of methods allowing you to insert of replace bits. You can also count backwards and forwards with an int representing the index (remember the 1st character is index 0). You can also find the first something after an index, or the last something before it.

One warning about counting from indices. If you find a "z" at index i, then looking for the next "z" after i will actually find the same "z". You might need to start looking from i + 1.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!