C string functions
Today I discovered the usefulness of string functions of C during my C programming exercises. The strcpy and strcat functions are similar to PHP statement $variable .= $var2, which adds the new value to the end of the previous value. The strlen function simply calculates the length of specified string variable. Here is the code I wrote:
/*
*
* scanfFirstLast.c
* Use string functions to process the input values
* by Robby Chen, 2010
*
*/
#include <stdio.h>
#include <string.h>
main() {
char name[50];Â Â Â Â Â Â // Input individual name
char fullName[100];Â Â Â // Combine first name and last name together
int length;Â Â Â Â Â Â // Length of the full name
printf("nPlease enter your first name: ");
scanf("%[^n]", name);Â Â Â // Enter the first name
// Dummy code to flush the input value
while (getchar() != 'n' && getchar() != EOF)
printf("%s", name);
strcpy(fullName, name);Â Â Â // Use strcpy function to assign the first name to fullName
printf("Please enter your last name: ");
scanf("%[^n]", name);Â Â Â // Enter the last name
strcat(fullName, " ");Â Â Â // Use strcat function to add a space to fullName to separate between first name and last name
strcat(fullName, name);Â Â Â // Add the last name to fullName
length = strlen(fullName);Â Â Â // Calculate the total length of fullName
// Output the result
printf("nYour full name is %s.n", fullName);
printf("The total length of your name is %d.nn", length);
}
C string
A string is an array of char data types and terminated by a null (0) character (also know as the first character in the ASCII character set). The null character is an invisible character in the end of a string. Therefore, always add a number to the length of the array when declaring the char array. For example, char name[21] where name originally contains 20 characters.
In order to assign value to the char array, use strcpy function in the standard C library (stdio.h). For example, strcpy(name, “Mark”). However, it gave me a warning when I tried to compile the source code using gcc. After I googled about the warning message “incompatible implicit declaration of built-in function ‘strcpy’”, I found out that I need to include string.h in addition to stdio.h. Perhaps it’s the difference between Dev-C++ compiler and gcc compiler.
To output to the screen using printf, use %s for string rather than %d for digit/integer. For instance, printf(“The contents of name are %sn”, name).
Here is source code for the basic string program:
#include <stdio.h>
#include <string.h>
main() {
char name[21];
strcpy(name, "Mark");
printf("The contents of name are %sn", name);
fflush(stdin);
getchar();
}