Why StringJoiner when we already have StringBuilder?

StringJoiner is very useful, when you need to join Strings in a Stream. As an example, if you have to following List of Strings: final List<String> strings = Arrays.asList(“Foo”, “Bar”, “Baz”); It is much more simpler to use final String collectJoin = strings.stream().collect(Collectors.joining(“, “)); as it would be with a StringBuilder: final String collectBuilder = … Read more

How to use StringBuilder wisely?

Modifying immutable structures like strings must be done by copying the structure, and by that, consuming more memory and slowing the application’s run time (also increasing GC time, etc…). StringBuilder comes to solve this problem by using the same mutable object for manipulations. However: when concatenating a string in compile time as the following: string … Read more

StringBuilder capacity()

When you append to the StringBuilder, the following logic happens: if (newCount > value.length) { expandCapacity(newCount); } where newCount is the number of characters needed, and value.length is the current size of the buffer. expandCapacity simply increases the size of the backing char[] The ensureCapacity() method is the public way to call expandCapacity(), and its … Read more

How to remove empty lines from a formatted string

If you also want to remove lines that only contain whitespace, use resultString = Regex.Replace(subjectString, @”^\s+$[\r\n]*”, string.Empty, RegexOptions.Multiline); ^\s+$ will remove everything from the first blank line to the last (in a contiguous block of empty lines), including lines that only contain tabs or spaces. [\r\n]* will then remove the last CRLF (or just LF … Read more

What is the difference between String and StringBuffer in Java?

String is used to manipulate character strings that cannot be changed (read-only and immutable). StringBuffer is used to represent characters that can be modified. Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable. You can … Read more

Is String.Format as efficient as StringBuilder

NOTE: This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? “format” : “args”); } … Read more