Modelling



Strings

Accessing individual parts of a string

An individual element is identified by using an index :

  • this is a number inside square brackets.
  • in PYTHON and JS the first element is always 0.

In this example, we can see that the 4th character is accessed

let myString = "Juniper berries"
console.log(myString[3])



Accessing a part of the String

Here we may want to access certain constiguos elements of the string. For this we use the function substr()

In this example, we want to get 5 characters starting from the 4th charcter. Notice that:

  1. substring is a method used on the string so it is attached to the string variable using a "dot"
  2. the first parameter is the index of the start character
  3. the second paramter is the number of characters to take

In this example, we can see that the 4th character is accessed and then 5 characters taken

let myString = "Juniper berries"
console.log(myString.substr(4, 5))

This would output "iper "



Accessing the length of the string

One of the most important operations on strings is to determine its length.

This is done in JavaScript using a method called length which is a property of the string object

This delivers a count of the number of characters in the string.

In this example, we can see that the length of the string should be 15

let myString = "Juniper berries"
console.log(myString.length)

Looping through a string - Method 1 using the index

Here we use a FOR loop.

This method has the instructions for the counter to change as part of the Loop code.

There is a TEST BEFORE every repetition - it is definite.

let myString = "Juniper berries"
//loop through string
    for (var index = 0; index < myString.length; index ++){
    console.log(myString[index])
}

Looping through a string - Method 2 using the object

Here we use a FOR loop.

This method just takes each character as an object as part of the Loop code.

let myString = "Juniper berries"
//loop through string
    for (character of myString){
    console.log(character)
}

Now model the code above in the modelling.js code