ziglings/exercises/006_strings.zig

52 lines
1.7 KiB
Zig
Raw Normal View History

2021-01-05 19:26:02 -05:00
//
// Now that we've learned about arrays, we can talk about strings.
2021-02-15 16:55:44 -05:00
//
2021-01-05 19:26:02 -05:00
// We've already seen Zig string literals: "Hello world.\n"
//
// Zig stores strings as arrays of bytes.
//
// const foo = "Hello";
//
// Is the same as:
//
// const foo = &[_:0]u8{ 'H', 'e', 'l', 'l', 'o' };
2021-01-05 19:26:02 -05:00
//
// Notice how individual characters use single quotes ('H') and
// strings use double quotes ("H"). These are not interchangeable!
//
2021-01-05 19:26:02 -05:00
const std = @import("std");
pub fn main() void {
const ziggy = "stardust";
// (Problem 1)
2021-01-05 19:26:02 -05:00
// Use array square bracket syntax to get the letter 'd' from
// the string "stardust" above.
const d: u8 = ziggy[???];
// (Problem 2)
2021-02-16 15:36:33 -05:00
// Use the array repeat '**' operator to make "ha ha ha ".
2021-01-05 19:26:02 -05:00
const laugh = "ha " ???;
// (Problem 3)
2021-01-05 19:26:02 -05:00
// Use the array concatenation '++' operator to make "Major Tom".
// (You'll need to add a space as well!)
const major = "Major";
const tom = "Tom";
const major_tom = major ??? tom;
// That's all the problems. Let's see our results:
2021-02-15 16:55:44 -05:00
std.debug.print("d={u} {s}{s}\n", .{ d, laugh, major_tom });
// Keen eyes will notice that we've put 'u' and 's' inside the '{}'
// placeholders in the format string above. This tells the
// print() function to format the values as a UTF-8 character and
// UTF-8 strings respectively. If we didn't do this, we'd see '100',
// which is the decimal number corresponding with the 'd' character
// in UTF-8. (And an error in the case of the strings.)
//
2021-01-05 19:26:02 -05:00
// While we're on this subject, 'c' (ASCII encoded character)
// would work in place for 'u' because the first 128 characters
// of UTF-8 are the same as ASCII!
//
2021-01-05 19:26:02 -05:00
}