Tuesday 15 January 2019

Strings

#Tutorial6#

Defining strings

Strings in C are actually arrays of characters. Although using pointers in C is an advanced subject, fully explained later on, we will use pointers to a character array to define simple strings, in the following manner:


char * name = "John Smith";
 
This method creates a string which we can only use for reading.
If we wish to define a string which can be manipulated, we will need to define it as a local character array:
char name[] = "John Smith";
This notation is different because it allocates an array variable so we can manipulate it. The empty brackets notation [] tells the compiler to calculate the size of the array automatically. This is in fact the same as allocating it explicitly, adding one to the length of the string:
char name[] = "John Smith";
/* is the same as */
char name[11] = "John Smith";
The reason that we need to add one, although the string John Smith is exactly 10 characters long, is for the string termination: a special character (equal to 0) which indicates the end of the string. The end of the string is marked because the program does not know the length of the string - only the compiler knows it according to the code.

String formatting with printf

We can use the printf command to format a string together with other strings, in the following manner:
char * name = "John Smith";
int age = 27;

/* prints out 'John Smith is 27 years old.' */
printf("%s is %d years old.\n", name, age);
Notice that when printing strings, we must add a newline (\n) character so that our next printf statement will print in a new line.

String Length

The function 'strlen' returns the length of the string which has to be passed as an argument:
char * name = "Nikhil";
printf("%d\n",strlen(name));
 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.