The Artima Developer Community
Sponsored Link

Java Answers Forum
Insert into String Buffer

1 reply on 1 page. Most recent reply: Oct 8, 2003 9:47 PM by Rahul

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Martin Völkening

Posts: 1
Nickname: mvoelkenin
Registered: Oct, 2003

Insert into String Buffer Posted: Oct 8, 2003 9:17 AM
Reply to this message Reply
Advertisement
Hi,

I have a StringBuffer 'buftext' that contains some text. I need to insert another text 'insertnew' before a given character 'before'. Every time I insert the text the length of the StringBuffer increases and that messes up my if part:

int buflength = buftext.length();
for(int i = 0; i < buflength; i++) {
String compare = buftext.substring(i,i+1);
if(compare.equals(before)) {
buftext.insert(i,insertnew);
buflength = buftext.length();
}
}

I get an infinite loop. Why does this happen and how can I solve it?

Thanks ...

Martin

PS I am just starting to learn Java ;-)


Rahul

Posts: 52
Nickname: wildhorse
Registered: Oct, 2002

Re: Insert into String Buffer Posted: Oct 8, 2003 9:47 PM
Reply to this message Reply
This happens because: You are inserting new text at a specified position, but in the next iteration you are getting the same 'compare' where you had inserted text in the previous iteration. That means the loop never gets past the first encounter with 'compare' and keeps finding it again and inserts text infinitely.

You must increase the counter 'i' with the length of the inserted text as well as the string with which you are comparing (so that you don't encounter it in the next iteration).

Flat View: This topic has 1 reply on 1 page
Topic: Read from a file in same directory Previous Topic   Next Topic Topic: Help with 6 errors basic stuff :p

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use