Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing "\n" with "<br> .. 4

Status
Not open for further replies.

Petal

Programmer
Jun 8, 2001
56
NO
I have a string where i wont to replace all occurens of &quot;\n&quot; with &quot;<br>&quot;.

How can _I do this?


 
replacing single characters is easy with Java, you just use the String.replace(oldChar char, newchar char) method.

However, replacing a word rather than a byte is causing someone else problems on this forum. I haven't looked at the thread yet, but the last time I did, no one had been able to resolve this issue.

I guess the long way around is to loop through the string (you can use charAt method) and just test for \ symbol. When you find it check to see if the next character is n, and if it is replace them all with your <br> string. Bearing in mind you will have to have logic that can create a new String object to extend the length of the old one (because <br> has more chars than \n).


Its a pain, but I can't think of anything else. Hope it helps.
 
Hi!
I think the thread your referring to was mine. I used this function and it works quite well:
Code:
String replace(String str, String text, String by) {
	// Replaces text with by in string
	    int strLength = str.length();
	    int txtLength = text.length();
	    if ((strLength == 0) || (txtLength == 0))
	    	return str;

	    int i = str.indexOf(text);
	    if ((i == 0) && (text != str.substring(0,txtLength))) return str;
	    if (i == -1) return str;

	    String newstr = str.substring(0,i) + by;

	    if (i+txtLength < strLength)
	        newstr += replace(str.substring(i+txtLength,strLength),text,by);

	    return newstr;
	}

to use it:
Code:
newString = replace(oldStr, &quot;oldWord&quot;, newWord&quot;);

hope that makes sense. :)
 
P.S: sorry if the coding's poor but I only started learning Java about two weeks ago and that code was converted from JavaScript X-)
 
btw: u might want to start using the StringBuffer object rather than String if you are expecting the String to change. Every time you make a change to a String object, a new object is created i.e. the old isn;t changed at all.

Better use of memory :)

also, if u add your String into an object of its own i.e. wrap it, you can then give the impression that the function is part of the object rather than an operation on the String. also it will be available to all instances of that class. something like this:

class MyString
{
private StringBuffer s;

public MyString( StringBuffer s )
{
this.s = s;
}

public StringBuffer replace( String s1, String s2 )
{
// Add your code here
}
}
 
Thanks..

but the function would not work..

I got this error message:

---------------------------------------------
JRun Servlet Error
---------------------------------------------

ImprovementPrintPreviewServlet19:

java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

---------------------------------------------

Do you understand it?
 
Thanks for that, like I said I'm very new to Java and I appreciate all the help I get :)

You couldn't expand on that code you gave could you? I'm not sure I entirely get what's going on with StringBuffer and why it only takes in two arguments and such.
TIA
Iain X-)
 
first of all joernaa, your array has not been created properly i.e. it was zero elements. so if you try and access anything in the array(that doesn't exist) you will get an java.lang.ArrayIndexOutOfBoundsException

now, shmmeee. instead of passing in the string and the other two arguements, you only need the 'replace this' && 'with that' arguements because the string itself IS part of your object. You already have it, its called s.
you had:
String replace(String str, String text, String by)
and i have
public StringBuffer replace( String s1, String s2 )

where text = s1 and by = s2. in this case str = s .

you understand????

a StringBuffer works exactly like a String on the face of it. If you are declaring String to be constant i.e. public final String, then a String is fine. otherwise just get into the practice of using the StringBuffer
 
Hi,

Something similar to what shmmeee has posted but this works incase you still can't get the other one to work. This is a class by itself so you can see how it works.

// abc.java
public class abc
{
public static void main(String[] args)
{
String abc = &quot;hello\nworld&quot;;
abc = replaceBreak(abc);
System.out.println(&quot;abc : &quot;+abc);
}
public static String replaceBreak(String temp)
{
int position = temp.indexOf(&quot;\n&quot;);
if (position == -1)
return temp;
else
{
String firstHalf = temp.substring(0,position);
String secondHalf = temp.substring(position+1,temp.length());
temp = firstHalf+&quot;<br>&quot;+secondHalf;
if (temp.indexOf(&quot;\n&quot;) != -1)
temp = replaceBreak(temp);
}
return temp;
}
}

Just copy the method replaceBreak over and remove the keyword 'static' like:-

public String replaceBreak(String temp)

Regards,
Leon
(p.s. this program uses recursion) If you need additional help, you can email to me at zaoliang@hotmail.com I don't guaranty that I will be able to solve your problems but I will try my best :)
 
Just a thought... I thought I saw a reference to a &quot;nl2br&quot; function in another thread...

Rose/Miros
 
Leon

You deserve a medal the amount of stuff you &quot;knock up in afew minutes&quot;.
 
Another way to do this would be to use a combination of StringTokeniser and StringBuffer, setting &quot;/n&quot; as the delimiter of the StringTokeniser, and appending &quot;<br>&quot; to each token when appending to the StringBuffer.

Something along the lines of
String outStr;
String inStr = &quot;the return character\nturned into a\nbr tag\n&quot;;
StringBuffer strB = new StringBuffer();
StringTokenizer strT = new StringTokenizer(inStr, &quot;\n&quot;, false);
while(strT.hasMoreTokens())
{
strB.append(strT.nextToken()).append(&quot;<br>&quot;);
}
outStr = strB.toString();

Greg
 
Greg has a good solution. One of the things that you all seem to have been overlooking is
that the original poster wanted to replace ALL occurances of &quot;\n&quot; and most of the solutions
given only replace a single occurance.

Charles
 
Hi Charles,

No offence, all the solutions given replace more than a single occurance. This includes the programs shmmeee and I have provided. You can see that we used recursion (that means we keep calling the same method). Wheras for the method LittleWing was saying, he was suggesting to use StringBuffer instead of normal String.

Pipk, I don't think I deserve any medals... not good enough for any yet :) anyway, thanks for saying that...boost my morale hehe :D If you need additional help, you can email to me at zaoliang@hotmail.com I don't guaranty that I will be able to solve your problems but I will try my best :)
 
Sorry Leon, I didn't see those recursive calls. Frankly though, I wouldn't use recursion to solve a problem like this and I didn't even think to look for it in the code. It is much to messy and is totally unnecessary. An iterative solution is much cleaner and much more extensible. Imagine using the recursive solution to process a huge string (such as a large text file). The memory footprint this would create because of all the object churn would be a waste of resources.

By the way, using a StringBuffer is a better way to go anyways because everytime you reassign a string variable you create a new object on the heap. This is fine for simple processing but it is not at all extensible from a performance standpoint.

Happy coding,

Charles
 
you guys!!! heloo....java has a &quot;replace&quot; method...jeezzz.... in any case....from experience watch out!!! you may need to fo this also for \r

ed
 
Hi Charles,

You are right about the wastage of resources. It didn't occur to me about it until LittleWing, Greg and you have mentioned it, something which I guess I need to buck up on perhaps... I don't have the habit of realising on how much resources I am wasting everytime.

ed: is the replace method that you are talking about found in the String class? If yes, the method accepts 2 char values as parameters. First, the character to be replaced and the second, the character to replace the first character. In this case, we are trying to replace '\n' with &quot;<BR>&quot;. So this method isn't applicable.

Best Regards,
Leon If you need additional help, you can email to me at zaoliang@hotmail.com I don't guaranty that I will be able to solve your problems but I will try my best :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top