006_strings.zig 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. const std = @import("std");
  15. pub fn main() void {
  16. const ziggy = "stardust";
  17. // (Problem 1)
  18. // Use array square bracket syntax to get the letter 'd' from
  19. // the string "stardust" above.
  20. const d: u8 = ziggy[???];
  21. // (Problem 2)
  22. // Use the array repeat '**' operator to make "ha ha ha ".
  23. const laugh = "ha " ???;
  24. // (Problem 3)
  25. // Use the array concatenation '++' operator to make "Major Tom".
  26. // (You'll need to add a space as well!)
  27. const major = "Major";
  28. const tom = "Tom";
  29. const major_tom = major ??? tom;
  30. // That's all the problems. Let's see our results:
  31. std.debug.print("d={u} {s}{s}\n", .{ d, laugh, major_tom });
  32. // Keen eyes will notice that we've put 'u' and 's' inside the '{}'
  33. // placeholders in the format string above. This tells the
  34. // print() function to format the values as a UTF-8 character and
  35. // UTF-8 strings respectively. If we didn't do this, we'd see '100',
  36. // which is the decimal number corresponding with the 'd' character
  37. // in UTF-8. (And an error in the case of the strings.)
  38. //
  39. // While we're on this subject, 'c' (ASCII encoded character)
  40. // would work in place for 'u' because the first 128 characters
  41. // of UTF-8 are the same as ASCII!
  42. //
  43. }