Guides:C/C Crash Course/Strings

From CoderGuide

Jump to: navigation, search

Back to TOC

Contents

Strings

The Standard C Library has a several useful functions for working with strings. They are:

char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
int strcmp(const char *s1, const char *s2);
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);
size_t strlen(const char *s);

There are more, but these are the only ones we will cover here.

In order to use these functions, you need to first include the string.h header file.

size_t strlen(const char *s)

strlen() function returns the length of a string.


/*Removes the newline from a string, if it exists*/
 
length=strlen(string)-1;
 
if(length>=0){
        if(string[length]=='\n')string[length-]=0;
}

size_t is a defined data type used for storing the size of things in memory, or on disk. Normally, it is a defined type of the largest integer data type the compiler has. A definition for the size_ttype might look like:

typedef size_t long long;

char *strcpy(char *dest, const char *src)

The strcpy() copies the contents of src into dest

3. If you want one string to hold the contents of another, you can't do it using the assignment operator '='. This is because, if you use the assignment operator, all you're doing is copying a reference to a pointer, not the data stored in it. The only exception to this is when you're initializing a string as such:

char *name[80]="Ima String";

Here, we've created a string with the contents, "Ima String", and the array name is still 80 elements long. Now, if we later do this:

name="Ima String";

We've assigned the reference of the string containing "Ima String" to name, which is an array of only 11 elements. We did not copy the string into the existing character array, instead, we just copied the reference into the name pointer which was holding a reference to the 80 element character array we defined before. So, a better way to copy this string would be to use the strcpy() function:

strcpy(name,"Ima String");

char *strncpy(char *dest, const char *src, size_t n)

strncpy()is almost the same as strcpy() except that it will only copy up to n bytes of src into dest and hence, is a safer function to use than strcpy() because it will prevent you from copying more data into the array than it has space to hold. However, if the length of the string src is bigger than the value of n then the null-terminator will not be added to the end of dest. This means, you will have to add it on your own (which is easy to do).


char *strcat(char *dest, const char *src)

The strcat() function, joins, or concats, two stings together. Basically, tacks on str onto the end of dest.

char *strcat(char *dest, const char *src, size_t n)

The strncat() performs essentially the same function of strcat(), except that it is safer to use, because it allows you to specify the maximum number of characters from src to add to dest. The null terminator for the string will always be added by strncat(), which is different behavior from strncpy().

The size of dest, must be at least the length of the string in dest plus n plus 1 (for the null terminator). Here is a safe way to use strncat():

   char dest[80];
 
      ...
      ...
 
   strncat(dest,src, 80-strlen(dest) );


int strcmp(const char *s1, const char *s2)

This function returns 0, if the strings match, less than zero if s1 is less than s2, and greater than zero if s1 is greater than s2. This can be troublesome because it doesn't return a boolean true (a non-zero) if the strings are equal. Instead, it returns a value that can assist in determine how one string relates to another, and hence assist in sorting strings. Here is some code that illustrates this:


/* strings-test.c -- a program to demonstrate comparing one string to another */
 
#include <stdio.h>
#include <string.h>
 
int main(){
 
        char s1[80]="",s2[80]="";
        for(;;){
                printf("Enter a string (type \"exit\" to exit):");
                gets(s1);
 
                /*check to see if the user typed in exit, exit loop
                  if he did*/
                if(!strcmp(s1,"exit"))break;
                printf("Enter another string:");
                gets(s2);
                if(strcmp(s1,s2)<0)
                        printf("\"%s\" < \"%s\"\n", s1,s2);
                if(strcmp(s1,s2)>0)
                        printf("\"%s\" > \"%s\"\n",s1,s2);
                if(strcmp(s1,s2)==0)
                        printf("\"%s\" == \"%s\"\n",s1,s2);
        }/*end for*/
}

The output looks like this:

Enter a string (type "exit" to exit):s1
Enter another string:s2
"s1" < "s2"
Enter a string (type "exit" to exit):aa
Enter another string:bb
"aa" < "bb"
Enter a string (type "exit" to exit):bb
Enter another string:cc
"bb" < "cc"
Enter a string (type "exit" to exit):bb
Enter another string:aa
"bb" > "aa"
Enter a string (type "exit" to exit):aa
Enter another string:aa
"aa" == "aa"
Enter a string (type "exit" to exit):a
Enter another string:a
"a " > "a"
Enter a string (type "exit" to exit):aa
Enter another string:a
"aa" > "a "
Enter a string (type "exit" to exit):a
Enter another string:aa
"a " < "aa"
Enter a string (type "exit" to exit):exit

There is also a strncmp() function, but it has limited use. strcmp() would stop comparing strings after it reaches a null terminator, so it's safe regardless of the size of the strings-- so long as there is a null terminator, and will continue until a zero is found somewhere in memory space, or your program crashes.

Personal tools