Strings in a program
The first program with strings: everything from steps 1 and 2, with fixed text so you can check the result by eye.
Create practice/09:
add_executable(p09_text text.c)
text.c:
int length(const char *s)is your ownstrlen: it counts bytes up to'\0'.const, because the function doesn't change the string.void to_upper(char s[])changes the string in place, hence noconst.touppergets(unsigned char)s[i].int copy_text(char t[], size_t size, const char *s)wrapssnprintfas in step 2: it returns how many characters were needed.main:sizeofandstrlenof the same array, "ąžuolas" in bytes,snprintfwithout cutting andcopy_textwith cutting,strchrto find the surname andstrcmpfor two comparisons.
Run it
p09_text and ▶:
name: "Ona"
sizeof: 20, strlen: 3, length: 3
word: strlen 9
Upper case: KAUNAS
Upper case: žALIAS
Full: Ona Petraite, strlen 12
Surname: Petraite
Fit: "Konstan", needed 12
Jonas comes before Ona
name and b are equal
Check every number: "Ona Petraite" is 11 letters and a space, hence 12, and "ąžuolas" has 7 letters but 9 bytes: ą and ž take 2 each.
If the Run window shows žALIAS instead of žALIAS, the program is right, but the window reads another encoding. In this topic the letters are the point, so set CLion's console to UTF-8: Settings → Editor → General → Console → Default Encoding: UTF-8, then run again.
A string in the debugger
A breakpoint at to_upper(city);, Debug. In the Variables window city shows as the text "Kaunas". Expand it: 20 boxes, and box [6] is 0 '\000' – that is the '\0'. F7 (Step Into) goes into to_upper: on every F8 watch s[i] change one at a time.
Commit: Add string basics.