How to compare strings in Java?
String comparison in Java In Java, string comparison is used to compare two string values for equality or inequality. There are two main ways to compare strings in Java: using …
Read Morelearn to code by examples
String comparison in Java In Java, string comparison is used to compare two string values for equality or inequality. There are two main ways to compare strings in Java: using …
Read MoreUsing String.join method (from java 8)
1 2 |
String[] array = new String[] { "a", "b", "c" }; String joined2 = String.join(",", array); |
Using simple for-loop expression
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); for (String n : name) { if (sb.length() > 0) sb.append(','); sb.append("'").append(n).append("'"); } return sb.toString(); |
Read More
Using java.util.formatter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // Optional locale as the first argument can be used to get // locale-specific formatting of numbers. The precision and width can be // given to round and align the value. formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); // -> "e = +2,7183" // The '(' numeric flag may be used to format negative numbers with // parentheses rather than a minus sign. Group separators are // automatically inserted. formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta); // -> "Amount gained or lost since last statement: $ (6,217.58)" |
See the Formatter docs for other modifiers.
Read MoreIn this article, we’ll look at the String array convert to String. This can be useful for example to log query parameters.
Read MoreSuppose you have the string ‘qwe’ and you need to repeat string ‘n’ times. Here’s how to do it: Using java 8 stream api
1 2 3 4 5 |
String newString = Collections.nCopies(3, "qwe").stream().collect(Collectors.joining("")); String newString = Stream.generate(() -> "qwe").limit(3).collect(Collectors.joining()); String newString = String.join("", Collections.nCopies(n, s)); |
Using String.format
1 2 3 4 |
String s = "qwe"; int n = 3; //this line print 'qweqweqwe' String newString = String.format("%0" + n + "d", 0).replace("0", s); |
Let us examine …
Read MoreTest strings equality == tests object references, .equals() tests the string values. Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical …
Read More