Want to keep learning?

This content is taken from the Monash University's online course, Creative Coding. Join the course to learn more.
The letters Aa in the typeface Sys by Fabrizio Schiavi

Strings in Processing

You’re already familiar with the String type introduced in week 1, but we haven’t made much use of it yet. As dealing with text will be important for the steps that follow, let’s take a closer look at how to process strings in Processing.

The String type is a little different from other simple types like char, int, float and boolean because it holds a variable-length sequence of characters rather than a single value.

Strings are always defined inside double quotes ( " ), whereas an individual char uses single quotes ('). If you want to include quotes inside a string, place a backslash (\) before them:

String s = "She said, \"that's not my hat\"";

String is in fact an object and so has a number of useful member functions and a few issues that you need to be aware of. We’ll be covering the basics of objects and object-orieted programming later this week.

There are several different ways to initialise a String:

String s1 = "I am the master of my own destiny!";
char data[] = {'N', 'I', 'C', 'E'};
String s2 = new String(data);
String s3 = new String(s1);

You’ve already seen the first method (s1). The second method (s2) creates a new string based an an array of characters, the {'N', 'I', 'C', 'E'} is called an initialiser list and is a simple way of loading arrays with initial data (we introduced these in week 3 on arrays ). Processing works out the length of the array (in this case 4) automagically.

The third method creates a new string that is a copy of s1. If I change s1 after this, s3 will not be affected.

One thing to be careful about is comparison of strings. If you want to test if two strings are equal, use the equals() member function:

if (s1 == s3) { ... } //  if s1 and s3 reference the same object
if (s1.equals(s3)) { ... } // if s1 and s3 have the same text

String also has a number of useful member functions:

  • charAt(index) returns the character at the specified index (same as an array)
  • indexOf(substr) and indexOf(substr, fromIndex) tests to see if substr is embedded in the string, returning the index of the first occurrence
  • length() returns the length of the string
  • substring(begin,end) returns the substring from the index begin up to end
  • toLowerCase() convert the string to lower case
  • toUpperCase() convert the string to UPPER CASE

More details can be found in the Processing reference.

You can append two strings together using the ‘+’ operator:

String s = s1 + s2;

The str() function is a handy function that can convert from other types to a string:

float e = 2.71
String s = str(e);

The split() and join() functions split or join a string into components based on a specified character to separate different parts:

String months = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
String rainfall = "2,0,14,29,47,18,78,76,211,23,11,38";
String monthList [] = split(months, ','); // split on ,
String rainList[] = split(rainfall, ',');
for (int i = 0; i < monthList.length; ++i)
    println("Rainfall for", monthList[i], "is: ", rainList[i]);

float [] rndNumberList = { random(1), random(1), random(1) };
String numbers = join(nf(rndNumberList, 1, 2), ",");

The first part of the code takes two strings, months and rainfall and slits them into an array of elements based on them being separated by a comma. Notice that to get the length of an array we use: array.length whereas to get the length of a String we use: string.length().

The second part of the code initialises an array with three random values, then joins there numeric values together as a single string separated by “,”. The nf() function is another handy utility for formatting numbers into strings. It takes an int [], float [] or int and creates a string with the number of digits to the left and right of the decimal point as the arguments specified. So after:

float f = 1.23456;
String s = nf(f,2,3);

The String s would have “01.234” in it (2 digits to the left of the decimal point, 3 digits after).

Functions like split() are useful for reading in data from things like spreadsheets (which can use the ‘comma separated values’ or CSV format), allowing you to do things like data visualisation.

Reading text from a file

Processing has many different functions to read and write data from files. We saw the saveFrame() function in week 1 for example.

Let’s briefly look at how to read lines of text from a file.

String lines[] = loadStrings("list.txt");

reads the text from ‘list.txt’ (in your sketch’s data directory) into the array lines, one line per array element so lines.length will give you the number of lines in the file.

loadStrings() also works with a URL so you can grab a text file from anywhere on the internet:

String lines[] = loadStrings("http://processing.org/about/index.html");

saveStrings() does what you’d expect: saves an array of strings to a file:

saveStrings("mydata.txt", lines);

By default, this file is saved to the sketch’s folder.

Share this article:

This article is from the free online course:

Creative Coding

Monash University

Get a taste of this course

Find out what this course is like by previewing some of the course steps before you join: