In Java, how to replace a symbol occurring in multiple places in the string by another symbol at all instances? -
i have written method replace first instance of given symbol symbol in given string.
i modify method replace instances of old symbol given new symbol in string.
public static string myreplace(string origstring, string oldvalue, string newvalue) { char[] chars = origstring.tochararray(); char[] charsnewvalue = newvalue.tochararray(); stringbuffer sb = new stringbuffer(); int startpos = origstring.indexof(oldvalue); int endpos = startpos + oldvalue.length(); int lengthofstring = origstring.length(); if (startpos != -1) { (int = 0; < startpos; i++) sb.append(chars[i]); (int = 0; < newvalue.length(); i++) sb.append(charsnewvalue[i]); (int = endpos; < lengthofstring; i++) sb.append(chars[i]); } else return toreplaceinto; return sb.tostring(); }
just use string.replace
. you've asked for:
replaces each substring of string matches literal target sequence specified literal replacement sequence.
slightly ot, method replacing first match more complex required, well:
private static string replaceone(string str, string find, string replace) { int index = str.indexof(find); if (index >= 0) { return str.substring(0, index) + replace + str.substring(index + find.length()); } return str; }
tests:
system.out.println(replaceone("find xxx find", "find", "rep")); // "rep xxx find" system.out.println(replaceone("xxx xxx find", "find", "rep")); // "xxx xxx rep" system.out.println(replaceone("xxx find xxx", "find", "rep")); // "xxx rep xxx" system.out.println(replaceone("xxx xxx xxx", "find", "rep")); // "xxx xxx xxx"
Comments
Post a Comment