Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Replace Problem

 
Eric Paul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm rather new to Java. I would like to know why the following code doesn't work. I'm trying to parse the String named "string". My delimiters are topic, location, presenter and end. I try to loop through the string to grab all three instances (you'll notice there are three topics). However, after the second loop, it resets itself and gives me the same output as the first pass. Any ideas?


 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

I'll bet that the replaceAll statement does nothing, and so newStmt = string.

Try something like "string = string.substring(string.indexOf(end) + end.length())". Then you don't need "newStmt".
 
Henry Wong
author
Marshal
Pie
Posts: 21116
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Basically...

First, outside of the loop, you extract the first item, but you don't print it...

Next, when you enter the loop, you remove the first item from the string, and you extract the second item. This (second item) is the first item that will be printed.

Next, on the next iteration of the loop, you remove the second item from the string. However, this is the orginal string, so all three items are still present, so you extract the first item again. This (first item) is the second item that will be printed.

Next, on the next iteration of the loop, you remove the first item from the string. However, this is the orginal string, so all three items are still present, so you extract the second item again. This (second item) is the third item that will be printed.

If your loop kept going, your program will be toggling between the first and second items...

Henry
 
Eric Paul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh, I see now. So, I'm only removing a piece of the string at any time. I actually need to:

1. Print the line I selected
2. Completely delete that from the string
3. Print the next line
etc.

I'll give it a shot. I may have more questions.
 
Eric Paul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, thanks for your help on this. This is how I ended up completing it. Probably not the most efficient way, but it works.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic