Computer Language
Lecture 9 - 2

Strings

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

May 10, 2025

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input and Strings
  3. Variables and calculation with numbers
  4. Conditional statements
  5. Repeating functionality
  6. Methods
  7. Lists, Arrays and Strings
  8. Midterm
  1. Introduction to Object Oriented Programming
  2. Deeper look into Object Oriented Programming
  3. Inheritance and Interfaces I
  4. Inheritance and Interfaces II
  5. Class diagrams, packages and exceptions
  6. Project Live Code Review and Evaluation
  7. Final examination

Agenda

  • Review of Strings basics
  • Split strings into several pieces

Learning objectives

  • Revising reading, printing and comparing Strings
  • Knowing how to split a string into several pieces

Strings review

  • Let’s first revise what we already know about Strings and see how to split them.
  • Below we create a String variable magicWord, that contains value "abracadabra".
String magicWord = "abracadabra";
  • Passing a String as a parameter to a print command (or, for that matter, any method that takes a String parameter) happens in the familiar way:
String magicWord = "abracadabra";
System.out.println(magicWord);

Sample Output

abracadabra

Reading and Printing Strings

  • You can read a string using the nextLine-method offered by Scanner.
  • The program below reads the name of the user and prints it:
Scanner reader = new Scanner(System.in);

System.out.print("What's your name?");
// reading a line from the user and assigning it to the name variable
String name = reader.nextLine();

System.out.println(name);

Sample Output

What's your name?
(user input) Vicky
Vicky

Concatenating Strings

  • Strings can also be concatenated.
  • If you place a +-operator between two strings, you get a new string that’s a combination of those two strings.
  • Be mindful of any white spaces in your variables!
String greeting = "Hi ";
String name = "Lily";
String goodbye = " and see you later!";

String phrase = greeting + name + goodbye;

System.out.println(phrase);

Sample Output

Hi Lily and see you later!

Comparing Strings

  • Strings can’t be compared with with the equals operator - ==.
  • For strings, there exists a separate equals-command, which is always appended to the end of the string that we want to compare.
String text = "chocolate";

if (text.equals("coffee")) {
    System.out.println("The text variable contains the text coffee.");
} else {
    System.out.println("The text variable does not contain the text coffee.");
}
  • The equals command is always appended to the end of the string that we want to compare, “string variable dot equals some text”.
  • You can also compare a string variable to another string variable.
String text = "itm comlang";
String anotherText = "itm oss";

if (text.equals(anotherText)) {
    System.out.println("The two texts are equal!");
} else {
    System.out.println("The two texts are not equal!");
}

Splitting a String

  • You can split a string to multiple pieces with the split-method of the String class.
  • The method takes as a parameter a string denoting the place around which the string should be split.
  • The split method returns an array of the resulting sub-parts.
  • In the example below, the string has been split around a space.
String text = "first second third fourth";
String[] pieces = text.split(" ");
System.out.println(pieces[0]);
System.out.println(pieces[1]);
System.out.println(pieces[2]);
System.out.println(pieces[3]);

System.out.println();

for (int i = 0; i < pieces.length; i++) {
    System.out.println(pieces[i]);
}

Output

first
second
third
fourth

first
second
third
fourth

Exercise 1 - Line by line

  • Write a program that reads strings from the user.
  • If the input is empty, the program stops reading input and halts.
  • For each non-empty input it splits the string input by whitespaces and prints each part of the string on a new line.

Sample Output

(user input) once upon a time
once
upon
a
time
(user input) a little program
a
little
program
(user input) halted
halted
 

Exercise 2 - AV Club

  • Write a program that reads user input until an empty line.
  • For each non-empty string, the program splits the string by spaces and then prints the pieces that contain av, each on a new line.

Sample Output

(user input) java is a programming language
java
(user input) navy blue shirt
navy

Sample Output 2

(user input) Do you have a favorite flavor
have
favorite
flavor
(user input) was it a cat?
  • Strings have a contains-method, which tells if a string contains another string.
  • It works like this:
String text = "volcanologist";

if (text.contains("can")) {
    System.out.println("can was found");
}

if (!text.contains("tin")) {
    System.out.println("tin wasn't found");
}

Sample Output

can was found
tin wasn't found

Data of Fixed Format

  • Splitting strings is used particularly when the data is of a fixed format.
  • This refers to data that adheres to some predefined format.
  • An example of this is the comma-separated values (csv) format, where commas are used to separate values.
  • Below you’ll find an example of data in csv form containing names and ages.
  • The first column contains names and the second one ages.
  • The columns are separated by a comma.
sebastian,2
lucas,2
lily,1

Processing data

  • Let’s assume the user enters the data above row by row, ending with an empty line.
  • A program to print the names and ages looks like the following:
Scanner reader = new Scanner(System.in);

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

String[] pieces = input.split(",");
    System.out.println("Name: " + pieces[0] + ", age: " + pieces[1]);
}

Sample Output

(user input) sebastian,2
Name: sebastian, age: 2
(user input) lucas,2
Name: lucas, age: 2
(user input) lily,1
Name: lily, age: 1

Exercise 3 - First words

  • Write a program that reads user input until an empty line is entered.
  • For each non-empty line the program splits the string by spaces and prints the first part of the string.

Sample Output

(user input) one two three four
one
(user input) this is a very important message
this

Exercise 4 - LastWords

  • Write a program that reads user input until an empty line is entered.
  • For each non-empty line the program splits the string by spaces and prints the last part of the string.

Sample Output

(user input) one two three four
four
(user input) this is a very important message
message

Secret messages

  • In the previous exercises, we actually implemented a very simple decrypting method for secret messages.
  • One variant of these hidden messages consists of getting the first character of each line.
  • For example, the secret message “program” is hidden in the (somewhat cryptic) text below.
Polymorphous computations elaborate.
Real calculators honour.
Older desktops deliver.
Great mainframes link.
Reversed devices install.
Additional workstations modem.
Many microcomputers letter.
  • Let’s continue along the same theme!
  • You can get a character at a specified index of a string with the charAt method.
String text = "Hello world!";
char character = text.charAt(0);
System.out.println(character);
H

Using diverse text

  • We’ve printed strings in the examples above.
  • Some of the data contained in a fixed-format string can be numerical.
  • In the previous data we used that contained names and ages, the ages were integers.
sebastian,2
lucas,2
lily,1
  • Splitting a string always produces an array of strings.
  • If the text is of fixed format, we can assume the data in a specific index to always be of a specific type e.g., in the example above, age at index 1 is an integer.

Processing integer data

  • The program below computes the sum of ages in this fixed format data.
  • In order to compute the sum, the age must first be converted to a number (the familiar command Integer.valueOf())
Scanner reader = new Scanner(System.in);
int sum = 0;

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

String[] parts = input.split(",");
    sum = sum + Integer.valueOf(parts[1]);
}

- System.out.println("Sum of the ages is " + sum);

Output

(user input) sebastian,2
(user input) lucas,2
(user input) lily,1

Sum of the ages is 5

More on processing integer data

  • We can write a program to compute the average of the ages in the same way:
Scanner reader = new Scanner(System.in);
int sum = 0;
int count = 0;

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

String[] parts = input.split(",");
    sum = sum + Integer.valueOf(parts[1]);
    count = count + 1;
}

if (count > 0) {
    System.out.println("Age average: " + (1.0 * sum / count));
} else {
    System.out.println("No input.");
}

Output

(user input) sebastian,2
(user input) lucas,2
(user input) lily,1

Age average: 1.666

Exercise 5 - Age of the oldest

  • Write a program that reads names and ages from the user until an empty line is entered.
  • The name and age are separated by a comma.
  • After reading all user input, the program prints the age of the oldest person.
  • You can assume that the user enters at least one person, and that one of the users is older than the others.

Sample Output

(user input) sebastian,2
(user input) lucas,2
(user input) lily,1
(user input) hanna,5
(user input) gabriel,10

Age of the oldest: 10

Exercise 6 - Name of the oldest

  • Write a program that reads names and ages from the user until an empty line is entered.
  • The name and age are separed by a comma.
  • After reading all user input, the program prints the name of the oldest person.
  • You can assume that the user enters at least one person, and the that one of the users is older than the others.

Sample Output

(user input) sebastian,2
(user input) lucas,2
(user input) lily,1
(user input) hanna,5
(user input) gabriel,10

Name of the oldest: gabriel

Length of a string

  • In the next exercise you’ll be asked for the length of the names.
  • You can find out the length of a string with length()-method:
String word = "equisterian";
int length = word.length();
System.out.println("The length of the word" + word + " is " + length);

Sample Output

The length of the word equisterian is 11

Exercise 7 - Personal details

  • Write a program that reads names and birth years from the user until an empty line is entered.
  • The name and birth year are separated by a comma.
  • After that the program prints the longest name and the average of the birth years.
  • If multiple names are equally longest, you can print any of them.
  • You can assume that the user enters at least one person.

Sample Output 1

(user input) sebastian,2017
(user input) lucas,2017
(user input) lily,2017
(user input) hanna,2014
(user input) gabriel,2009


Longest name: sebastian
Average of the birth years: 2014.8

Sample Output 2

(user input) sauli,1948
(user input) tarja,1943
(user input) martti,1936
(user input) mauno,1923
(user input) urho,1900


Longest name: martti
Average of the birth years: 1930.0

Checking our learning objectives

  • Revising reading, printing and comparing Strings
  • Knowing how to split a string into several pieces

Next week

  • Introduction to Object Oriented Programming

Acknowledgements


Back to title slide Back to lecture slides index