Concatenate A String In Dart
Code snippet for how to Concatenate A String In Dart with sample and detail explanation
The Dart programming language is an easy language to comprehend because it is concise and expressive. This article provides a concise tutorial on how to concatenate a string in Dart, which is a useful feature in string manipulation and further enhances the versatility of the language.
Code snippet for String Concatenation in Dart
void main() {
String str1 = "Hello";
String str2 = "World";
String res = str1 + ' ' + str2;
print(res);
}
When you run the program, the output will be “Hello World”.
Code Explanation for String Concatenation in Dart
The dart:core library provides built-in functions and classes like String, which includes methods for manipulating strings. In the provided Dart code snippet, we are concatenating two strings.
-
Start by defining the function
main()
, which is the entry point of every Dart program. -
Inside the
main()
function, we declare two string variables,str1
, andstr2
, and assign them the values “Hello” and “World” respectively.
String str1 = "Hello";
String str2 = "World";
- The next line of code is where the actual concatenation of the strings happens. We create a new string
res
and use the ’+’ operator to concatenatestr1
, a space in single quotes, andstr2
together.
String res = str1 + ' ' + str2;
- Finally, we use the
print()
method to output the resulting string to the console.
print(res);
The whitespace between the single quotes is used to introduce space between the words “Hello” and “World”. Without it, the output would be “HelloWorld”. This example demonstrates the simplest form of string concatenation in Dart. You can manipulate multiple strings in a similar manner using the ’+’ operator.