namrata shahade
namrata shahade

Reputation: 183

Convert the string into stringBuilder in java

I have one method which returns the string but I want the data inside the method in StringBuilder and convert it into string then how can I do it?

  public String[][] getDataOfJD(List<JobDescriptionField> jdFields) {
  int i = 0;
  String [][] data = new String[jdFields.size()][];
  for(JobDescriptionField field : jdFields) {
      if (i > 0){
          String messages = "";
          for (String message : field.getMessages()){
             messages += message;
          }
     data [i] = new String[]{field.getTitle(), field.getField(), messages, field.getScore() + ""};
  }
    i++;
    score = score + field.getScore();
  }
  return data;
  }

From above example field.getTitle(), field.getField() are of String type And if I want the data in StringBuilder and needs to convert it into string but if I tried to do it by return data.toString then it is giving error. Please Help me.

Upvotes: 12

Views: 75295

Answers (5)

Atal Amitabh
Atal Amitabh

Reputation: 1

String s="babad"
int l=1;
int r=3;
StringBuilder longpalin=new StringBuilder();
//Convert String s to StringBuilder
longpalin = new StringBuilder(s.substring(l,r+1));

//will convert StringBuilder into String
System.out.println(longpalin.toString())

Upvotes: 0

rahul
rahul

Reputation: 930

String str = "rahul";
System.out.println(str.getClass().getName());   
StringBuilder sb1 = new StringBuilder(str); // way 1
StringBuilder sb2 = new StringBuilder(); // way 2
sb2.append(str);
System.out.println(sb1.getClass().getName());
System.out.println(sb2.getClass().getName());

I hope the code above explains everything.

Upvotes: 1

ifelse.codes
ifelse.codes

Reputation: 2389

StringBuilder has a constructor that accepts string

https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#StringBuilder(java.lang.String)

StringBuilder sb = new StringBuilder("my string");

Upvotes: 0

lincollincol
lincollincol

Reputation: 862

Convert String to StringBuilder

String someText = "something...";
StringBuilder sb = new StringBuilder(someText);

Upvotes: 8

Cary
Cary

Reputation: 270

To create a StringBuilder from a String simply:

StringBuilder sb = new StringBuilder("MyString");
String s = sb.toString();

But as was said StringBuilder and StringBuffer are different. Take a look here for more information on StringBuilder and StringBuffer

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

Difference between StringBuilder and StringBuffer

Upvotes: 19

Related Questions