Search code examples
stringdartconcatenation

Is there a short form to concat a string with another one into the same variable in dart?


I want to build a string like this:

String mainString = "Hello, \n";
mainString = mainString + "World";
print(mainstring);

Is there a way to do this in dart without having to repeat the variable? Example of what I want done in perl:

my $main_string = "Hello, \n";
$main_string .= "World";
print($main_string);

Solution

  • You can write you code like this instead which are shorter:

    void main() {
      String mainString = "Hello, \n";
      mainString += "World";
      print(mainString);
    }
    

    If you are going to concatenating a lot of strings (like e.g. in a loop) it is much more efficient to use StringBuffer to append the strings and then create the String object from the StringBuffer like:

    void main() {
      final sb = StringBuffer("Hello, \n");
      sb.write("World");
      print(sb.toString());
    }
    

    The reason is by using the StringBuffer we don't need to create a new String object each time we concatenating a String to it.