06_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. //
  33. // Keen eyes will notice that we've put a 'u' inside the '{}'
  34. // placeholder in the format string above. This tells the
  35. // print() function to format the values as a UTF-8 character.
  36. // If we didn't do this, we'd see '100', which is the decimal
  37. // number corresponding with the 'd' character in UTF-8.
  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. }