Skip to content

Instantly share code, notes, and snippets.

@MisterBrash
Last active April 14, 2024 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MisterBrash/77f2a405eb29fe787ee9176cef9cc4d7 to your computer and use it in GitHub Desktop.
Save MisterBrash/77f2a405eb29fe787ee9176cef9cc4d7 to your computer and use it in GitHub Desktop.
ICS3U Lesson 3.2 - Looping Through Strings

3.2 - Remember Strings?

ICS3U - Mr. Brash 🐿️

Table of Contents

Brief Recap of Strings

A single letter is called a character (char).

Each character is a symbol (drawing) tracked by a number in the computers' memory. The computer looks-up the symbol, based on that number.

Many characters together is called a String of characters. Like a string of Christmas lights.

  • Ex: The word hello is a string made of the chars 'h' 'e' 'l' 'l' 'o'.
  • The first letter (char) is at position zero.
  • A char is primitive. They're very boring. Not much we can do with them.
  • A String is an object. Lots of neat properties and functions are available to them.
    • Strings have a very important property: .length which gives the number of all characters in the String.
  • It is very important to remember that "a" and "A" are considered different. "Hello" != "hello"
  • Note: JavaScript treats single letters as a String, not a char.

We can "build" a String using the concatonate feature of the + operator:

let my_output = "";
let t = "third";

my_output += "First" + " " + "second" + t;

return my_output;    // returns "First secondthird"

That will become very handy later.

New Information

A property is a fact about an object.

  • Strings have a very important property that we've seen before: .length
    let myString = "Hello World!";
    console.log(myString.length);   // Prints 12 to the screen

A function - also known as a method - is something that an object can do to manipulate data or give a result.

  • Strings have lots of useful functions but the ones we might focus on are:
    .charAt()
    .toUpperCase() and .toLowerCase()
    .charCodeAt()
    .substring()
    and many more, with awesome examples at w3schools!

  • Another very useful tool is the ability to get a character based on its code (number). For that we use String.fromCharCode() and give the Unicode number.

    let my_char = String.fromCharCode(64);   // the @ character
    console.log(my_char);  // @

Examples

Don't forget! To get a single character from the string we can use .charAt(index) or the shortcut of [index].

Now that we know a loop, we can loop through a string and print one character at a time!

let longText = "Supercalifragilisticexpialidocious";
let current_letter = 0;

while (current_letter < longText.length) {
  console.log(longText[current_letter]);
  current_letter++;
}

We can also build a String, if necessary:

Simple Example:

// duplicate the string as many times as requested
function duplicate(str, number_of_times) {
  let output = "";    // Empty string for building
  let n = 1;

  while (n <= number_of_times) {
    output += str;
  }

  return output;
}

// What will repeated_string be?
let repeated_string = duplicate("Yay Code!", 100);

More Complicated Example:

// Build a new string that does not have any spaces
let output = "";
let sample_text = "This is a sentence with spaces";
let n = 0;

while (n < sample_text.length) {
  // The character code for a space is 32
  if (sample_text.charCodeAt(n) != 32) {
    // Replace "with" with "without" and skip ahead the appropriate amount
    if (sample_text[n] == "w") {
      output += "without";
      n += 3; // Skip past "with"
    } else {
      output += sample_text[n];
    }
  }
  // Make sure we go ahead one character
  n++;
}

console.log(output);    // Thisisasentencewithoutspaces

Your Task

Inside your Unit 3 folder, make a new code file called 3.2 - Strings.js

Try creating the following functions:

  • reverse(str) Print the reverse of the given string to the console.
    Examples:

    reverse("Hello");
    "olleH"
    reverse("Coding's great!");
    "!taerg s'gnidoC"
  • dragons_and_goblins(str) For this function a string of random letters is passed in (for example dragons_and_goblins("dbhfghfgdbchdnwjdg")). Your job is to count how many dragons ("d") and goblins ("g") are encountered. Print the result to the console as shown in the examples below:

    dragons_and_goblins("dbhfghfgdbchdnwjdg");
    "Dragons: 4 Goblins: 3"
    dragons_and_goblins("pgoggl45j6ng jk*&j3 h^gg%h");
    "Dragons: 0 Goblins: 6"
  • add(str) You will be given a string of all single-digit numbers. Add them up and return the result.
    Examples:

    console.log(add("9350701"));
    25
    console.log(add("11111111112222255"));
    30
  • add_subtract(str) The same as the add() function except if you encounter a "-" symbol, the next number is subtracted from the total. Return the result.
    Example:

    console.log(add_subtract("543-36-9"));
    6
    console.log(add_subtract("0-102-53-3-1-5"));
    -10



🐿️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment