Tom Cheng
Tom Cheng

Reputation: 19

how to replace string with string

i need to replace each second letter in every word with string expression

public static void main(String[] args) {

     StringBuffer stbf=new StringBuffer("la la la");
     int k=1;
     String a= "wkj" ;
     String s1 = null;
     for(int i=0;i<3;i++){
         stbf.insert(1, a);
     }
     System.out.println(stbf);

as a result i want to see lwkj lwkj lwkj

Upvotes: 0

Views: 68

Answers (3)

BalaMurugan.N
BalaMurugan.N

Reputation: 118

String str = "la la la";
String answer = str.replaceAll("a", "wkj");
System.out.println("Replace String Is: " + answer);

str.replaceAll("a", "wkj")

Upvotes: 0

Kevin B&#246;ckler
Kevin B&#246;ckler

Reputation: 86

without giving a full solution to the problem, here are some hints:

  1. You should split your input string (example was "la la la") into distinct words. Use e.g. String.split(" ").

  2. You can then process every single word, keeping the first character, inserting your replacement string (example was "wkj") and appending third and any other character following. To do this, you could use String.substring(0, 1) to obtain the first character and all characters starting by the third character position (String.substring(2)). Have a look at the String api.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Hope that helps.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522636

String input = "la la la";
String replacement = "wkj";
String output = input.replaceAll("\\b(\\w)\\w", "$1"+replacement);
System.out.println("input: " + input);
System.out.println("output: " + output);

The regex \b(\w)\w will match the first two characters of each word in the sequence, and the replacement uses the first (captured) character, appended to the replacement.

Output:

la la la
lwkj lwkj lwkj

Upvotes: 4

Related Questions