DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Substring/Slice of a String

A Substring or Slice of a string, is a way to create a new string from an existing string. This technique usually is completed without allocation for the new string.

"hello world"

"o wor"

C# and Java

These languages provide a string class which are considered immutable as they don't expose methods s to modify the string.

The Substring (C#) and substring(Java) are used to create new strings from an existing one.

// C#
Console.WriteLine("hello world".Substring(4,5));
Enter fullscreen mode Exit fullscreen mode

We supply the starting index of the original string, then specify the length of the new string. You can leave off the second number if you want it to go the end of the original.

// Java
System.out.println("hello world".substring(4,9));
Enter fullscreen mode Exit fullscreen mode

While similar in syntax, the second argument is the index of the where the string ends in the original.

Python

# Python
print("hello world"[4:9])
Enter fullscreen mode Exit fullscreen mode

The Python language includes a specific syntax, which resembles that used for indexing. Here the second number is an index specifier for where the slice ends within the original array.

Like C# the second number can be left out to include to the end of the original.

# Python
print("hello world"[4:])
Enter fullscreen mode Exit fullscreen mode

Javascript

// Javascript
"Hello world!".slice(4, 9);
Enter fullscreen mode Exit fullscreen mode

Javascript takes its behavior from Python, utilizing an index rather than length for its second parameter.

Unicode

Not a single one of these will protect you from splitting surrogates.

It is possible for this method to work well for your use case, even if unicode is within the string.

Even my preferred language requires consideration of the unicode details.

Latest comments (0)