---
title: "string (C)"
type: concept
related: [String, Char]
source: https://www.jemoka.com/posts/kbhstring/
confidence: high
status: active
---

In C, string is an array of chars. C strings don&rsquo;t track their length; each C string always end in an null-terminating character: \0. This is represents the zero byte.
There&rsquo;s a built in function strlen which checks the length of a string without the null-terminating character. This function is O(n)!!!
String Pointer Syntax Sugar Synonyms char str[6]; // these are equivalent char *ptr = str; char *ptr = &amp;str[0]; char *ptr = &amp;str; // DON&#39;T DO THIS // these are equivalent char thirdLetter = str[3]; char thirdLetter = *(str + 3); seven commandments of c strings if we create a string as char[], we can modify its characters because its memory lives in our stack instead of living in a global data segment we can&rsquo;t set char[] as equaling to something, because its not strictly a pointer and instead it refers to an entire block of memory instead of a pointer to the first element (in a same vein, an array&rsquo;s size is fixed and travels with the variable) if we pass char[] as a parameter, it is converted to a char * if we create a string with new string literal as char *thing = &quot;thing&quot;, we can&rsquo;t modify it because its on the global data segment we can set char * equaling to another value because its a pointer adding an offset to a c string gives a substring that&rsquo;s places past the first character if we change characters in a string parameter, these changes will persist passing strings around Strings are passed as a pointer to their first character.
void foo(char *str) { // do string things } char string[6]; // THIS IS A STRING OF LENGTH 5!!!! (beacuse there&#39;s a null terminator) foo(string); // pass the syntax sugar pointer foo(&amp;string[0]); // pass the actual first pointer you won&rsquo;t know whether or not this is the address to a string or a pointer to a single character; so good practice to call it something_str if you&rsquo;d like a string.
character manipulation checker #include &lt;ctype.h&gt; int main() { isalpha(ch); islower(ch); ... } string manipulations #include &lt;string.h&gt; strcmp When you comparing strings, you can&rsquo;t use == or &lt; or &gt;. Instead:
#include &lt;string.h&gt; int main() { int cmp = strcmp(str1, str2); if (cmp == 0) { // if str1 is equal to str2 } else if (cmp &lt; 0) { // if str1 comes before str2 lexographically } else { // if str2 comes before str1 lexographically } } strcpy Copying strings, dangerously, because buffer overflows are fun.
This function does NOT care about buffer overflows, and WILL put in a null terminator.
strncopy This function optimize against buffer overflow, but it may not write a null terminator.
strcat strncat always puts in a null terminator.
pointer arithmetic with strings Fortunatly, each char is
strspn Count the number of characters that are &ldquo;cool&rdquo;: contained within the end
