Lecture 08 Strings

Joseph Haugh

University of New Mexico

Free Recall

  • Get out a sheet of paper or open a text editor
  • For 2 minutes write down whatever comes to mind about the last class
    • This could be topics you learned
    • Questions you had
    • Connections you made

Java vs Python: Strings

Java

  • Must use double quotes ("")
  • Can be empty
String s1 = "Maelle";
String s2 = "";

Python

  • Can use either single ('') or double ("") quotes
  • Can be empty
s1 = "Maelle"
s2 = ''

Strings

  • Strings are a sequence of characters
  • Characters are separate in Java
    • Denoted with single ('') quotes

    • Only a single character allowed inside

      char c1 = 'j';
      char c2 = 'H';
      char c3 = 'he'; // ERROR

String Concatenation

  • Strings can be concatenated(combined) using the + operator
void main() {
    String s1 = "Hello";
    String s2 = "World";

    String s3 = s1 + s2;

    IO.println(s3);            // Prints: HelloWorld
    IO.println(s1 + " " + s2); // Prints: Hello World
}

Plus Again?

  • Wait isn’t plus (+) used to add numbers?
  • It can do both!
  • This is called operator overloading
  • It allows one operator to behave differently based on its arguments
    • When given numbers it performs addition
    • When given strings it performs concatenation
    • When mixed it defaults to concatenation
void main() {
    int a = 5;
    int b = 7;
    IO.println(a + b);               // Prints: 12
    IO.println("Sum is " + a + b);   // Prints: Sum is 57
    IO.println("Sum is " + (a + b)); // Prints: Sum is 12
    IO.println(a + b + "boo");       // Prints: 12boo
}

PEMDAS

  • Expressions in Java generally follow the order of operations you learned in school, PEMDAS
    • Parenthesis before
    • Exponentiation before
    • Multiplication and division before
    • Addition and subtraction
void main() {
    int a = 3;
    a = 2 * a + 1;
    int b = 2;
    IO.println(a + "/" + b + "= " + a / b);
}

Prints: 7/2= 3

Methods

  • Methods are functions we can call on a given variable with a type such as a String

  • We call methods using the following syntax:

    <<variableName>>.<<methodName>>(<<argList>>);
  • For example, we can check if two Strings are equal using the equal method. We cannot use the == operator on Strings to check for equality:

    void main() {
        String s1 = "CS152";
        String s2 = "CS";
        s2 += "152";
        IO.println(s1.equals(s2)); // true
        IO.println(s1 == s2);      // false
    }

== vs equals

  • == is used to check for equality of primitive types
    • This includes:
      • int, char, boolean, double, etc.
      • Primitive types always start with a lower case letter
      • These are types which are baked into the language
  • equal is used to check for equality of reference types
    • This includes:
      • Strings, Arrays, Lists, etc.
      • Reference types usually start with an upper case letter
      • These are types which are defined in the language itself

String Methods: Length

  • We can determine the length of a string using the length method:
void main() {
    String s1 = "Maelle";
    String s2 = "Verso";
    IO.println(s1.length() + s2.length()); // Prints: 11
}

String Methods: charAt

  • We can get the character at a given index using the charAt method.
  • You must be careful to make sure the index exists
void main() {
    String s1 = "Maelle";
    IO.println(s1.charAt(0)); // Prints: M
    IO.println(s1.charAt(5)); // Prints: e
    IO.println(s1.charAt(6)); // ERROR
}

String Methods: toUpperCase

  • We can force all characters in a string to be upper case using the toUpperCase method
  • Note that this function returns a new string which is upper cased
  • It leaves the original string unchanged!
void main() {
    String s1 = "Maelle";
    s1.toUpperCase();
    IO.println(s1); // Prints: Maelle
    s1 = s1.toUpperCase();
    IO.println(s1); // Prints: MAELLE
}

String Methods: substring

  • We can extract a substring from a string using the substring method
  • The substring method given one argument means it starts at the index we give it and goes to the end of the string
  • The substring method given two arguments means it starts at the index we give it and goes up to but not including the second index
void main() {
    String s1 = "Maelle";
    IO.println(s1.substring(2));    // Prints: elle
    IO.println(s1.substring(3, 5)); // Prints: ll
}

Looping Over Strings

  • We can loop over strings using the charAt function
  • For example we could print out all the characters at even indexes:
void main() {
    String s1 = "expedition33";
    for (int i = 0; i < s1.length(); i++) {
        if (i % 2 == 0) {
            char c = s1.charAt(i);
            IO.println(c);
        }
    }
}

Creating Strings With Concatenation

  • What if instead of printing out the individual even index characters we wanted to create a new string with them?

    void main() {
        String s1 = "expedition33";
        String result = "";
        for (int i = 0; i < s1.length(); i++) {
            if (i % 2 == 0) {
                char c = s1.charAt(i);
                result += c;
            }
        }
        IO.println(result);
    }
  • IntelliJ may warn you do change this, don’t listen!