This week's book giveaway is in the Spring forum.
We're giving away four copies of Spring in Action (5th edition) and have Craig Walls on-line!
See this thread for details.
Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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: 61727
193
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!