006_strings.zig 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // Now that we've learned about arrays, we can talk about strings.
  3. //
  4. // We've already seen Zig string literals: "Hello world.\n"
  5. //
  6. // Zig stores strings as arrays of bytes.
  7. //
  8. // const foo = "Hello";
  9. //
  10. // Is the same as:
  11. //
  12. // const foo = [_]u8{ 'H', 'e', 'l', 'l', 'o' };
  13. //
  14. // Notice how individual characters use single quotes ('H') and
  15. // strings use double quotes ("H"). These are not interchangeable!
  16. //
  17. const std = @import("std");
  18. pub fn main() void {
  19. const ziggy = "stardust";
  20. // (Problem 1)
  21. // Use array square bracket syntax to get the letter 'd' from
  22. // the string "stardust" above.
  23. const d: u8 = ziggy[???];
  24. // (Problem 2)
  25. // Use the array repeat '**' operator to make "ha ha ha ".
  26. const laugh = "ha " ???;
  27. // (Problem 3)
  28. // Use the array concatenation '++' operator to make "Major Tom".
  29. // (You'll need to add a space as well!)
  30. const major = "Major";
  31. const tom = "Tom";
  32. const major_tom = major ??? tom;
  33. // That's all the problems. Let's see our results:
  34. std.debug.print("d={u} {s}{s}\n", .{ d, laugh, major_tom });
  35. // Keen eyes will notice that we've put 'u' and 's' inside the '{}'
  36. // placeholders in the format string above. This tells the
  37. // print() function to format the values as a UTF-8 character and
  38. // UTF-8 strings respectively. If we didn't do this, we'd see '100',
  39. // which is the decimal number corresponding with the 'd' character
  40. // in UTF-8. (And an error in the case of the strings.)
  41. //
  42. // While we're on this subject, 'c' (ASCII encoded character)
  43. // would work in place for 'u' because the first 128 characters
  44. // of UTF-8 are the same as ASCII!
  45. //
  46. }