06_strings.zig 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 'u' and 's' inside the '{}'
  34. // placeholders in the format string above. This tells the
  35. // print() function to format the values as a UTF-8 character and
  36. // UTF-8 strings respectively. If we didn't do this, we'd see '100',
  37. // which is the decimal number corresponding with the 'd' character
  38. // in UTF-8. (And an error in the case of the strings.)
  39. //
  40. // While we're on this subject, 'c' (ASCII encoded character)
  41. // would work in place for 'u' because the first 128 characters
  42. // of UTF-8 are the same as ASCII!
  43. //
  44. }