Java string replacement

Source: Internet
Author: User

Java's string and stringbuffer do not provide a substring replacement function. To implement this function, you must write your own function. The following are two implementation methods: method 1, use regular expression replacement (in fact, the regular expression is not actually used. The pattern parameter of the compile function. likes the regular expression string to be treated only as the literal value ).

Import java. util. RegEx .*;

Public class test {

Public static void main (string [] ARGs ){

String S = "My name is Xinyu! ";

Replacefromstring (S, "name", "nickname ");

System. Out. println (s );

}

Public static void replacefromstring (string string1, string string2, string string3 ){

String newstring = pattern. Compile (string2, pattern. Literal). matcher (string1). replaceall (string3 );

System. Out. println (newstring );

}

}

Method 2: Use the indexof string to find the sub-string, add the content before the original string and the replacement string to the stringbuffer, and only find the original string)

/**

* @ Author Hans Bergsten, gefion software (www.gefionsoftware.com)

*/

Public class stringutils {

/*** Returns a string with all occurrences of the string from * Replaced by the string.

** @ Return the new string */

Public static string replaceinstring (string in, string from, string ){

Stringbuffer sb = new stringbuffer (in. Length () * 2 );

String posstring = in. tolowercase ();

String cmpstring = from. tolowercase ();

Int I = 0;

Boolean done = false;

While (I <in. Length ()&&! Done ){

Int start = posstring. indexof (cmpstring, I );

If (START =-1 ){

Done = true;

} Else {

SB. append (in. substring (I, start) + );

I = start + from. Length ();

}

}

If (I <in. Length ()){

SB. append (in. substring (I ));

}

Return sb. tostring ();

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.