For loops and strings

Dart supports the same loops as many other C-influenced languages: the for, while, and do while loops. In this example, you'll see a for loop, which you'll use to reverse a string.

Strings can be included in single quotes ('Dart') or double quotes ("Dart"). The escape character is . So, for instance, you could write the following:

String myString = 'Throw your 'Dart'';

And the myString variable would contain Throw your 'Dart'For our example, let's begin with the main() method:

void main() {
String myString = 'Throw your Dart';
String result = reverse(myString);
print (result);
}

Nothing major to note here. We are just setting a string and calling a reverse method, which will reverse the string, to print the result.

So let's write the reverse() method next:

String reverse(String old) {
int length = old.length;
String res = '';
for (int i = length-1; i>=0; i--) {
res += old.substring(i,i + 1);
}
return res;
}

Strings are actually objects, so they have properties, for example, length. The length property of a string, quite predictably, contains the number of characters of the string itself. 

Each character in a string has a position, beginning at 0In the for loop, first, we declare an i variable and set it to an initial value of the length of the string, minus one. The next two steps are setting the condition (or exit criteria) and the increment. The loop will keep repeating until i is equal to, or bigger than, 0, and at each repetition, it will decrease the value of i by one.

What this means is that starting at the end of the string, we will loop until we reach the beginning of the string.

The += operator is a concatenation. This is a shortened syntax for res = res + old.substring(i,i + 1);.

The substring() method returns part of a string, starting at the position specified at the first parameter, included, and ending at the position specified at the second parameter. So, for example, the following code would print Wo:

String text = "Hello World";
String subText = text.substring(5,8);
print (subText);

There's actually another way that we could extract a single character from a string, instead of using the substring() method: using the position of the character itself in the string.For example, instead of writing this:

res += old.substring(i,i + 1);

We could also write the following code:

res += old[i];

The end result of the full code that we have written is shown here:

You'll never need to write a code like this in a real-world application. You can achieve the same result just by writing this:

 String result = myString.split('').reversed.join(); 

Next, you'll see two features that we will use extensively throughout the book: the arrow syntax and the ternary operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74