006_strings.zig 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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[???];
  26. // (Problem 2)
  27. // Use the array repeat '**' operator to make "ha ha ha ".
  28. const laugh = "ha " ???;
  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. }