006_strings.zig 1.7 KB

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