web123456

Java String splicing three ways "+", "", "", line feed splicing "\r\n"

When doing feature development, it will often be necessary to splice multiplestring (computer science)For example, in the request address on the parameter splicing, return an information description of the field needs to be spliced more than one sub-segment, etc., then we commonly used to solve the following three ways, the first is also more commonly used and simple, directly with the + sign for splicing string string, splicing in the case of fewer fields is still available, more than the case of the possibilities of performance will be poor, the second is to use () formatting way to The second is to use () to format the string, and the last is to use () to complete the splicing.

Note: Sometimes the content information needs to be followed by a line break in the next paragraph, then the standard line break "\r\n" can be spliced in.

I. "+" splicing

  1. String s = "a" + "b";
  2. (s); // ab

II. ()

Commonly used conversion characters are as follows:

  • Generic Floating Point Number: A shorter format output than %f, %a, showing 6 valid digits and rounding.

  • Hash code: Instead of using a lengthy linear search technique to find a key, a special value called a "hash code" is used. The hash code takes the information in the object and converts it to a "relatively unique" integer (int) for that object. All objects have a hash code.

  1. String ss = ("a%s", "b");
  2. (ss); // ab

III. ()

  1. String s = "a" + "b";
  2. StringBuilder stringBuilder = new StringBuilder();
  3. (s).append("c").append(3);
  4. (stringBuilder); //abc3

IV. Line feed splicing "\r\n"

  1. String s = "aaaaaaa" + "b";
  2. StringBuilder stringBuilder = new StringBuilder();
  3. String c = (s).append("\r\n").append(3).toString();
  4. (c);
  5. // The output is as follows:
  6. aaaaaaab
  7. 3

V. Summary:

  • StringBuilder Best Performance

  • String's '+' splice, performance close to StringBuilder, the bottom is actually StringBuilder, better readability

  • Weakest performance with better code readability

  • Readability is really up to the individual, you get used to it when you use it a lot.