Characters and Strings

In this lesson:
  • Intro to the char variable
  • Arrays of char
  • How to print a string using printf
  • How C strings are terminated
Running time: 12:53
 
 

Comments (3)

 
Hello mr.Runchman, You may also declare & initilize a string of text as following:
char OneLineOfText[80] = "This is a test";
printf("%s", OneLineOfText);

Please take note of the double quotes, as apposed to single quote chars. The double quote tells the compiler we will be using a 'string literal' or a complete sentence(s).
Yes, entirely true, thanks for the additional info.

A question I received from a viewer:

I have a question about inserting special characters in your string that output as the character versus being interpreted by the compiler. For instance, let's say that you want to display the \0 in a string output rather than the \0 being interpreted as the null character. Furthermore, how do you process "" or ' in your functions so that they display correctly as output?

My answer:

Generally, when you toss a \ in front of a character, it tells the compiler to treat the next character literally, rather than doing something special with it. For example, say you want your string to be "this is a "special" test" (i.e. quotes within the string). You do this like:

strcpy(oneLineOfText,"this is a \"special\" test");

the slash before the quotes kinda says "Hey this isn't the end of my string, it's just a quote".

Similarly with single quotes:
printf("This is a \'single\' quoted word");

As far as the \0, if you are asking how you'd display something like "this is a null char: \0" or something like that, you'd:

printf("This is a null char: \\0");

notice the double slash - the first one says "Treat the next character as a literal", so the compiler just prints the next backslash, rather than processing it. After it prints the \, the 0 afterward is just printed as a zero since the compiler treated the slash before it as just a character.