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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String.replace() with unusual characters

Status
Not open for further replies.

OhioSteve

MIS
Mar 12, 2002
1,352
US
I can do this with String.replace():
String line= "Mary had a little lamb.";
line= line.replace('a','x');

But I want to do these things:
String line= "Mary had a little lamb.";
line= line.replace([period character],'x');

String line= "Mary had a little lamb.";
line= line.replace([carriage return],[comma]);

I want to use .replace with punctuation marks and invisible characters. But the compiler freaks out whenever I attempt this. I strongly suspect that ascii or unicode values are somehow involved in this. Can you tell me the specific syntax that I need to use.



 
Here is my test code:

Code:
public class Test
{
	public static void main(String args[])
	{
		String str = "Hello,\nworld!\n";
		System.out.println(str);
		
		str = str.replace('\n', ' ');
		str = str.replace(',', '!');
		System.out.println(str);
		
		System.exit(0);
	}
}
If you test my code, you see that the replacements for a new line and a comma work just fine. Test out my code to check to see if this code works with your compiler. Let me know what happens.

Nick Ruiz
Webmaster, DBA
 
if newline is part of your string, use
"s1"+(new Character((char)10)).toString()+"s2
 
The char '.' is a literal '.'

The string "." is evaluated as a regular expression in the replace call.

To escape this, try using "\\." instead. The first '\' escapes the second '\', so that the character sequence passed to the regular expression engine is '\' '.'

This then ensures the period is not treated as a special metacharacter.

One way to get round this problem for large pieces of text is:

"\\Q your text containing metachars like . + *\\E"

See also:

Cheers, Neil
 
You are right. "\n" does force a carriage return. Where can I get a list of all of the codes like that?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top