Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Replace any string between two substrings

 
Arun Suresh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a string
String a = "-d -k dfgherewrdjyfdf\"";
where 'dfgherewrdjyfdf' is a password of unknown length.
I want to replace dfgherewrdjyfdf with *****.
so that the final string looks like:
-d -k *****"
preferably i will like to replace anything between -k and ".
i could not find any one go solution with replaceall, regex or anywhere...

any help will be appreciated.

Arun
[ November 24, 2008: Message edited by: Arun Suresh Kumar ]
 
Roland Maurer
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

this should work :

String a = "-d -k dfgherewrdjyfdf\"";
a = a.replace(a.substring(a.indexOf("-k") + 2, a.lastIndexOf("\"")), " *********");
System.out.println(a);
 
Arun Suresh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent.
That worked perfectly.
Your help is highly appreciated.
Thanks,
Arun
 
Roland Maurer
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That worked perfectly

thats good
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'd like to check for absence of the sub strings. If indexOf or lastIndexOf returns -1 you will get a StringIndexOutOfBoundsException.
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Arun Suresh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thankyou everyone who has replied.
ciao
cheers
Arun
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic