Home > Refactorings > Refactorings for concatenating and splitting strings

Refactorings for concatenating and splitting strings

November 25th, 2011

Concatenation is the process of appending one string to the end of another string. A string is basically a sequence of Unicode characters. An important property of strings is that they are read-only (immutable). Once a string has been created, it cannot be changed. So, when a string is updated, the .NET framework actually discards the original string and creates a new string. In other words, the concatenation of strings is creating an entirely new string, allocating enough memory for everything, copying all the data from the existing values of all concatenated strings and then copying the data from each string. As the string grows, the amount of data it has to copy each time grows too. Having already concatenated strings allows you to avoid such problems.

DevExpress Refactor! Pro has a simple refactoring to combine strings called Concatenate Strings. This refactoring concatenates all selected strings into a single string. Here’s its preview hint for the selected strings:

Refactoring - Concatenate Strings preview

When concatenating verbatim and non-verbatim strings, they are combined into a common format depending on the type of a first string. If the first string is verbatim, then the resulting string will be also verbatim, otherwise not.

The opposite of this refactoring is the Split String refactoring. This refactoring is also very simple. It can break the active string into two or three pieces depending on the editor caret position and the selection state. If you select a part of a string, this part will be extracted into a new string and combined with two other start and end parts:

Refactorings - Split String selection preview

If there’s no string selection, only two parts are produced by breaking the string into two pieces:

Refactorings - Split String caret preview

The refactoring may be useful for localization purposes, especially if some part of a string is already localized, but the other one is not yet localized. Here, you can split the string:

Refactorings - Split String for localization preview

and replace its parts to localized versions:

Refactorings - Extract String to Resource preview

Bear in mind that if the editor caret is positioned at an unbreakable sequence of characters, such as a string format item (e.g. “{0}”), an escape character (e.g. “\r”, “\n”), a unicode character code (e.g. “\uFFFF”), or the editor caret is at the very beginning or an end of a string, the refactoring will not be available in these cases.

Also, refer to other refactorings that work with strings.

Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Dec/02/2011
ID: R044

Similar Posts: