PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How to append String to StringBuffer variable in JAVA

 May 12, 2022     append, java, output, string, stringbuffer     No comments   

Issue

My code is as below. i need to add single quotes for each word in string with single quotes after appending DD to it.

public class Main
{
    public static void main(String[] args) {
        String ChkboxIds = "'a1b2c3','321cba','123abc'";
        String checkBoxId = null;
        String checkId = null;
        StringBuilder checkIDS = new StringBuilder("'");
        for(int i=0;i<=ChkboxIds.split(ChkboxIds, ',').length;i++){
            checkBoxId = "DD"+ChkboxIds.split(",")[i].replace("'","")+","+checkBoxId;
            checkId = checkBoxId.substring(0, checkBoxId.length() - 5);
            System.out.println("---PRINT---"+checkId);
            for(int j=0;j<i;j++){
                checkIDS..append('\'').append(checkId.split(",")).append('\'').append(',');
                System.out.println("---PRINT123----"+checkIDS);
            }
        }
    }
}

I have tried using StringBuffer too. please point your answers here. The output i get is some junk data while i need the words with dd attached at the start.

Expected output:'DDa1b2c3','DD321cba','DD123abc'


Solution

Problem

  • issue at .append(checkId.split(",")) where you append an String[] so it's representation is it's hashcode

  • don't need a second loop, each word need one loop round, no inner loop needed

  • your split is wrong, you need ChkboxIds.split(","), you don't need with the same string as delimiter


Fix

You can do much more simpler than that

  • split on comma
  • remove quotes, append DD, add quotes
  • save at same place in array
  • join array with comma
String chkboxIds = "'a1b2c3','321cba','123abc'";

String[] splitted = chkboxIds.split(",");
String checkBoxId;

for (int i = 0; i < splitted.length; i++) {
    checkBoxId = "DD" + splitted[i].replace("'", "");
    splitted[i] = "'" + checkBoxId + "'";
}

String result = String.join(",", splitted);
System.out.println(result);
// 'DDa1b2c3','DD321cba','DD123abc'

Regex power

String chkboxIds = "'a1b2c3','321cba','123abc'";
String result = chkboxIds.replaceAll("'(\\w+)'", "'DD$1'");


Answered By - azro
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing