Dart Substring

To find the substring of a string in Dart, call substring() method on the String and pass the starting position and ending position of the substring in this string, as arguments.

Syntax

The syntax of String.substring() method is

String.substring(int startIndex, [ int endIndex ])

where substring is located in the range [startIndex, endIndex) in this String, excluding the character at endIndex.

endIndex is optional, if no endIndex is provided, substring is taken till the end of the string.

ADVERTISEMENT

Examples

Substring of a String with Start and End Index

In this example, we will take a String and find the substring of it defined by starting index and ending index.

main.dart

void main(){
	
	String str = 'HelloTutorialKart.';
	
	int startIndex = 5;
	int endIndex = 13;
	
	//find substring
	String result = str.substring(startIndex, endIndex);
	
	print(result);
}

Output

Tutorial

The index range of the given string is

H   e   l   l   o   T   u   t   o   r   i   a   l   K   a   r   t   .
 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
                     ^****************************   ^
               startingIndex                    EndingIndex

Substring without Ending Index

In this example, we will take a String and find the substring of it defined by starting index. No ending index shall be provided as argument to substring() method. In this case, length of the string is taken as ending Index, implicitly by Dart.

main.dart

void main(){
	
	String str = 'HelloTutorialKart.';
	
	int startIndex = 5;
	
	//find substring
	String result = str.substring(startIndex);
	
	print(result);
}

Output

TutorialKart.

The index range of the given string is

H   e   l   l   o   T   u   t   o   r   i   a   l   K   a   r   t   .
 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
                     ^************************************************
               startingIndex

Conclusion

In this Dart Tutorial, we learned how to find substring of a string given starting index and an optional ending Index.