06_strings.zig 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. // Like the C language, Zig stores strings as arrays of bytes
  7. // encoded as UTF-8 characters terminated with a null value.
  8. // For now, just focus on the fact that strings are arrays of
  9. // characters!
  10. //
  11. const std = @import("std");
  12. pub fn main() void {
  13. const ziggy = "stardust";
  14. // Use array square bracket syntax to get the letter 'd' from
  15. // the string "stardust" above.
  16. const d: u8 = ziggy[???];
  17. // Use the array repeat '**' operator to make "ha ha ha".
  18. const laugh = "ha " ???;
  19. // Use the array concatenation '++' operator to make "Major Tom".
  20. // (You'll need to add a space as well!)
  21. const major = "Major";
  22. const tom = "Tom";
  23. const major_tom = major ??? tom;
  24. std.debug.print("d={u} {}{}\n",.{d, laugh, major_tom});
  25. // Going deeper:
  26. // Keen eyes will notice that we've put a 'u' inside the '{}'
  27. // placeholder in the format string above. This tells the
  28. // print() function (which uses std.fmt.format() function) to
  29. // print out a UTF-8 character. Otherwise we'd see '100', which
  30. // is the decimal number corresponding with the 'd' character
  31. // in UTF-8.
  32. // While we're on this subject, 'c' (ASCII encoded character)
  33. // would work in place for 'u' because the first 128 characters
  34. // of UTF-8 are the same as ASCII!
  35. }