0

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

2
  • So what is your code doing now ? and what you are expecting ? Commented Feb 2, 2017 at 5:48
  • stbf=stbf.replaceAll("la", "lwkj"); will do the trick Commented Feb 2, 2017 at 6:05

3 Answers 3

4
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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.