Learn/Julia/8. Strings and a small project
Lesson 8 of 8
Sign in

Julia, lesson 8

Strings and a small project

You have been building strings since lesson 1. This lesson fills in the toolbox, then puts the whole course to work in one program.

Characters and length

A String is a sequence of characters. length(s) counts them, and s[i] gives you a Char at position i (starting at 1). Strings cannot be changed in place; every string function returns a new string.

Positions in a string count bytes, not characters. For plain English text that makes no difference, but with letters like é some positions fall in the middle of a character and give an error. When you need to visit every character, loop over the string itself: for c in word ... end always works.

Changing and cleaning

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Expense report

Press Ctrl Enter or Check to test your code.

replace takes a pair old => new, the same arrow you used to build dictionaries.

Searching

To keep only some characters, filter works on strings as well: filter(isletter, "R2-D2!") gives "RD". isletter, isdigit and isspace test single characters.

Splitting and joining

split(s) cuts a string at runs of whitespace and ignores spaces at the ends. split(s, ",") cuts at every comma instead. join does the reverse:

Formatting numbers

String interpolation prints numbers in their natural form, so money can come out as 4.5 instead of 4.50. The Printf standard library gives you exact control with the @printf macro, which uses the same codes as many other languages:

%-8s left-aligns text in 8 columns, %6.2f right-aligns a number in 6 columns with 2 decimals. @sprintf does the same but returns the string instead of printing it. lpad and rpad are a lighter option for padding text.

A small project

The second exercise is an expense report that uses everything so far: reading input, parsing numbers, a dictionary to group, sorting, a loop, a function, and formatted output. Grow it in small steps and run it each time: first print each parsed line, then the totals, then the formatting.

Further reading

  • Julia manual: Strings
  • Julia docs: String functions
  • Julia docs: Printf

Each input line is a phrase. A phrase is a palindrome if its letters read the same forwards and backwards, ignoring case, spaces and punctuation. For each line print yes or no.

Sample input:

Sample output:

Each input line is an expense in the form category,amount, for example food,12.50. Spaces around the parts may appear and should be ignored, and categories should be treated case-insensitively (store them in lower case).

Print one line per category in alphabetical order, formatted with @printf("%-10s%8.2f\n", category, total). Then print a line of 18 dashes, a line with the grand total formatted as @printf("%-10s%8.2f\n", "total", grand_total), and finally Biggest: category for the category with the largest total (the alphabetically first one if there is a tie).

Sample input:

Sample output:

word = "Julia"
length(word)    # 5
word[1]         # 'J', a Char
word[2:3]       # "ul", a String
uppercase("tea")              # "TEA"
lowercase("TEA")              # "tea"
uppercasefirst("tea time")    # "Tea time"
strip("   hi  ")              # "hi"
replace("a-b-c", "-" => "+")  # "a+b+c"
reverse("stressed")           # "desserts"
repeat("ab", 3)               # "ababab"
occursin("cat", "concatenate")    # true
startswith("README.md", "READ")   # true
endswith("photo.png", ".png")     # true
words = split("  the quick   brown fox ")   # ["the", "quick", "brown", "fox"]
join(words, "-")                            # "the-quick-brown-fox"
using Printf
@printf("%-8s %6.2f\n", "Lunch", 4.5)   # "Lunch      4.50"
Never odd or even
Hello
A man, a plan, a canal: Panama!
yes
no
yes
food,12.50
transport, 3.20
Food,7.25
fun,15
food         19.75
fun          15.00
transport     3.20
------------------
total        37.95
Biggest: food