Topic : Introduction to C Programming
Author : Mkoubaa
Page : << Previous 10  Next >>
Go to page :


has to count the characters until it finds '\0'. This fact makes C much slower than Pascal in certain cases, but in others it makes it somewhat faster, as we will see in the examples below.
Because C provides no explicit support for strings in the language itself, all of the string-handling functions are implemented in libraries. The string I/0 operations (gets, puts, and so on) are implemented in <stdio.h>, and a set of fairly simple string manipulation functions are implemented in <string.h> (on some systems, <strings.h> ).
The fact that strings are not native to C forces you to create some fairly roundabout code. For example, suppose you want to assign one string to another string; that is, you want to copy the contents of one string to another. In Pascal, this task is easy:

program samp;  
var    
    s1,s2:string;  
begin    
    s1:='hello';  
    s2:=s1;  
end.


In C, as we saw in tutorial 12, you cannot simply assign one array to another. You have to copy it element by element. The string library (<string.h> or <strings.h> ) contains a function called strcpy for this task. The following code shows how to use strcpy to achieve the same results in C as in the Pascal code above:

#include <string.h>
void main()  
{    
    char s1[100],s2[100];    
     strcpy(s1,"hello"); /* copy "hello" into s1 */    
    strcpy(s2,s1);      /* copy s1 into s2 */  
}


strcpy is used whenever a string is initialized in C. Another major difference between Pascal and C is the way they handle string comparisons. In Pascal, unlike in C, string compares are built into the language. In C, you use the strcmp function in the string library, which compares two strings and returns an integer that indicates the result of the comparison. Zero means the two strings are equal, a negative value means that s1is less than s2, and a positive value means s1 is greater than s2. In Pascal, the code looks like this:

program samp;  
var    
    s1,s2:string;  
begin    
    readln(s1);    
    readln(s2);    
    if s1=s2 then      
        writeln('equal')    
    else if (s1<s2) then      
        writeln('s1 less than s2')    
    else      
        writeln('s1 greater than s2');  
end.

Here is the same code in C:

#include <stdio.h>  
#include <string.h>
void main()  
{    
    char s1[100],s2[100];
     gets(s1);    
    gets(s2);    
    if (strcmp(s1,s2)==0)      
        printf("equal\n");    
    else if (strcmp(s1,s2)<0)      
        printf("s1 less than s2\n");    
    else      
        printf("s1 greater than s2\n");  
}


Other common functions in the string library include strlen , which returns the length of a string, and strcatwhich concatenates two strings. The string library contains a number of other functions, which you can peruse by reading the man page. Note that many of the standard Pascal capabilities, such as copy, delete, pos, and so on, are missing.
To get you started building string functions, and to help you understand other programmers' codes-everyone seems to have his or her own set of string functions for special purposes in a program-we will look at two examples, strlen and strcpy. Following is a strictly Pascal-like version of strlen:

int strlen(char s[])  
{    
    int x;
    x=0;    
    while (s[x] != '\0')
         x=x+1;    
    return(x);  
}
  

Most C programmers shun this approach because it seems inefficient. Instead, they often use a pointer-based approach:

int strlen(char *s)  
{    
    int x=0;
    while (*s != '\0')    
    {      
        x++;      
        s++;    
    }    
    return(x);  
}


You can abbreviate this code to the following:

int strlen(char *s)  
{    
    int x=0;
    while (*s++)      
        x++;    
    return(x);  
}


I imagine a true C expert could make this code even shorter.
When I compile these three pieces of code on a MicroVAX with gcc, using no optimization, and run each 20,000 times on a 120-character string, the first piece of code yields a time of 12.3 seconds, the second 12.3 seconds, and the third 12.9 seconds. What does this mean? To me, it means that you should write the code in whatever way is easiest for you to understand. Pointers generally yield faster code, but the strlen code above shows that that is not always the case.
We can go through the same evolution with strcpy:

strcpy(char s1[],char s2[])  
{    
    int x;
    for (x=0; x<=strlen(s2); x++)      
        s1[x]=s2[x];  
}


Note here that <= is important in the for loop because the code then copies the '\0'. Be sure to copy '\0'. Major bugs occur later on if you leave it out, because the string has no end and therefore an unknown length. Note also that this code is very inefficient, because strlen gets called every time through the for loop. To solve this problem, you could use the following code:

strcpy(char s1[],char s2[])  
{    
    int x,len;
     len=strlen(s2);    
    for (x=0; x<=len; x++)      
        s1[x]=s2[x];  
}


The pointer version is similar.

strcpy(char *s1,char *s2)  
{    
    while (*s2 != '\0')    
    {      
        *s1 = *s2;      
        s1++;      
        s2++;    
    }  
}


You can compress this code further:

strcpy(char *s1,char *s2)  
{    
    while (*s2)      
        *s1++ = *s2++;  
}


If you wish, you can even say while (*s1++ = *s2++);. The first version of strcpy takes 415 seconds to copy a 120-character string 10,000 times, the second version takes 14.5 seconds, the third version 9.8 seconds, and the fourth 10.3 seconds. As you can see, pointers provide a significant performance boost here.
The prototype for the strcpy function in the string library indicates that it is designed to return a pointer to a string:

char *strcpy(char *s1,char *s2)

Most of the string functions return a string pointer as a result, and strcpy returns the value of s1 as its result.
Using pointers with strings can sometimes result in definite improvements in speed and you can take advantage of these if you think about them a little. For example, suppose you want to remove the leading blanks from a string. To do this in Pascal, you might use the delete function in one of two ways, the most obvious way being the following:

program samp;  
var    
    s:string;  
begin    
    readln(s);    
    while (s[1] <> ' ') and (length(s)>0) do      
      


Page : << Previous 10  Next >>