Search This Blog

Saturday, May 26, 2012

String


STRINGS
WHAT IS A STRING?
A string is a group of characters, usually letters of the alphabet. In order to format our printout in such a way that it looks nice, has meaningful names and titles to output of our program, we need the ability to output text data.
·         A complete definition of a string is a series of char type data terminated by a null character.
·         In C there is no special data types for strings, strings are just the array of characters terminated by null ‘\0’ character with ASCII value 0
·         For example, to hold a string of six characters, we need to declare an array of
      type char with seven elements. Arrays of type char are declared like arrays of
      other data types. For example, the statement char string[7]; used to hold six char
When C is going to use a string of data in some way, either to compare it with another string, output it, copy it to another string, or whatever, the functions are set up to do what they are called to do until a null, is detected.
Initializing Character Arrays (String)
·         Like other C data types, character arrays can be initialized when they are
           declared. Character arrays can be assigned values element by element, as shown
           here:
char string[10] = { `K', `a', `t', `h',  `m', `a', ‘n’, ‘d’, ‘u’,`\0' };
·         It's more convenient to use a literal string, which is a sequence of characters enclosed in double quotes:
char string[10] = "Kathmandu"; which is same as above.
·         If you don't specify the number of subscripts when you declare an array, the compiler calculates the size of the array for you. Thus, the following line creates and initializes an six-element array:
char string[] = "Patan";
Strings and Pointer
Since strings are stored in arrays of type char, with the end of the string marked by the null character. So the name of string always points the beginning of the string. We can use array name to access that string. To pass a string to any functions, we pass the array name. The same is true of the string display functions printf() and puts()

Allocating Memory for string:
Static allocation: Declaring string as array
Dynamic Allocation : Declaring string as pointer.

The start of a string is indicated by a pointer to a variable of type char. So we can declare the string with pointer as:
char *str;
This statement declares a pointer to a variable of type char named str. It doesn't point to anything now, but what if we changed the pointer declaration to read
char *str = "This is a string declaration.";
When this statement executes, the string "This is a string declaration." (with a terminating null character) is stored somewhere in memory, and the pointer str is initialized to point to the first character of the string. We needn't worry where in memory the string is stored; it's handled automatically by the compiler.
The preceding declaration/initialization is equivalent to the following, and the two notations *str and str[] also are equivalent; they both mean "a pointer to.".
The malloc() Function
The malloc() function is one of C's memory allocation functions. When we call malloc(), we pass it the number of bytes of memory needed. malloc() finds and reserves a block of memory of the required size and returns the address of the first byte in the block. We don't need to worry about where the memory is found; it's handled automatically. The malloc() function returns an address, and its return type is a pointer to type void. A pointer to type void is compatible with all data types. Because the memory allocated by malloc() can be used to store any of C's data types, the void return type is appropriate.
#include <stdlib.h>
void *malloc(size_t size);
malloc() allocates a block of memory that is the number of bytes stated in size. By allocating memory as needed with malloc() instead of all at once when a program starts, we can use a computer's memory more efficiently. When using malloc(), we need to include the STDLIB.H header file. Some compilers have other header files that can be included; for portability, however, it's best to include STDLIB.H.
malloc() returns a pointer to the allocated block of memory. If malloc() was unable to allocate the required amount of memory, it returns null. Whenever we try to allocate memory, we should always check the return value, even if the amount of memory to be allocated is small.
An example:
#include <stdlib.h>
#include <stdio.h>
void main()
{
   /* allocate memory for a 100-character string */
   char *str;
   if (( str = (char *) malloc(100)) == NULL)
   {
     printf( "Not enough memory to allocate \n");
     exit(1);
   }
   printf( "String was allocated!"\n );
}


Displaying Strings
String display is usually done with either the puts() function or the printf() function.
The puts() Function
The puts() function puts a string on-screen--hence its name. A pointer to the string to be displayed is the only argument puts() takes. puts() can be used to display literal strings as well as string variables. The puts() function automatically inserts a newline character at the end of each string it displays, so each subsequent string displayed with puts() is on its own line.
/* Demonstrates displaying strings with puts(). */

  #include <stdio.h>

  char *message1 = "C";
  char *message2 = "is the";
  char *message3 = "best";
  char *message4 = "programming";
  char *message5 = "language!!";

  main()
  {
     puts(message1);
     puts(message2);
     puts(message3);
     puts(message4);
     puts(message5);

    return 0;
 }

output
C
is the
best
programming
language!!
The printf() Function
            The printf() function can be used to display literal strings as well as string variables but it prints all the string in one line until the \n character is encountered. It takes the argument either literal string or control character %s and corresponding string variable(pointer)
            Example
 char *str = "A message to display";
printf("%s", str);
or
printf(“A message to display “);

Inputting Strings Using the gets() Function
The gets() function gets a string from the keyboard. When gets() is called, it
reads all characters typed at the keyboard up to the first newline character (which we generate by pressing Enter). This function discards the newline, adds a null character, and gives the string to the calling program. The string is stored at the location indicated by a pointer to type char passed to gets(). A program that uses gets() must #include the file STDIO.H.
an example.
 /* Demonstrates using the gets() library function. */

  #include <stdio.h>

  /* Allocate a character array to hold input. */

  char input[81];

  main()
 {
     puts("Enter some text, then press Enter: ");
     gets(input);
     printf("You entered: %s\n", input);
     puts(input);

     return 0;
 }
output
Enter some text, then press Enter:
This is a test
You entered: This is a test
This is a test
Inputting Strings Using the scanf() Function
To read a string, include the specifier %s in scanf()'s format string. Like gets(), scanf() is passed a pointer to the string's storage location.
scanf(“%s”, str);  equivalent to  gets(str);
We can read in multiple strings with scanf() by including more than one %s in the format string. For each %s in the format string, scanf() uses the same  rules as printf() to find the requested number of strings in the input.
For example:
scanf("%s%s%s", s1, s2, s3);

Some useful String Handling functions in C library:
 Header file: <string.h>

  • strlen(s) returns the length of string ‘s’ without taking into account the terminal ‘\0’
  • srtcpy(s1,s2): copies the string s2 to string s1.
/* Demonstrates strlen() and  strcpy().  */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
 void  main()
 {
    char dest1[80];    /*array declaration */
     char dest2;      /* Pointer declaraction */
    printf("\nsource: %s", source );
    printf(“\n Length of source string is %d”, strlen(source));
/*must allocate memory for dest2 since declaration is pointer type */
  /* Copy to dest1 is okay because dest1 points to  80 bytes of allocated space. */
     strcpy(dest1, source);
     printf("\ndest1:  %s", dest1);

     /* To copy to dest2 you must allocate space. */
    dest2 = (char *)malloc(strlen(source) +1);
     strcpy(dest2, source);
     printf("\ndest2:  %s\n", dest2);

}
Output
source: The source string.
Length of Source string is  18
dest1:  The source string.
dest2:  The source string.
  • strcat(s1,s2) : appends string ‘s2’ at the end of  ‘s1’. It also called concatenation. So strcat(s1,s2) concats the strings s1 and s2.
/* Demonstration of the strcat() function. */

  #include <stdio.h>
  #include <string.h>
  char str1[27] = "a";
  char str2[2];
 void main()
 {
     int n;
     /* Put a null character at the end of str2[]. */
     str2[1] = `\0';
     for (n = ‘b’; n<=’z’; n++)
     {
         str2[0] = n;
         strcat(str1, str2);
         puts(str1);
     }
}
The output:
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
abcdefghijk
abcdefghijkl
abcdefghijklm
abcdefghijklmn
abcdefghijklmno
abcdefghijklmnop
abcdefghijklmnopq
abcdefghijklmnopqr
abcdefghijklmnopqrs
abcdefghijklmnopqrst
abcdefghijklmnopqrstu
abcdefghijklmnopqrstuv
abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvwxy
abcdefghijklmnopqrstuvwxyz
  • strcmp(s1, s2) : Compares two strings ‘s1’ and ‘s2’ and returns negative, zero or positive if  ‘s1’ is less than , equal or greater then the string ‘s2’ . It compares all the characters of one string one by one with character of other string. If all the characters of both string  are same, returns 0 . if at any point the characters are different,  it returns the difference of two characters.
  • strncpy(s1,s2,n) : copies first n characters from string s2 to string s1. If string s2 is less than n characters, then the entire string s2 will be copied to s.
/* demo of strncpy() */
#include <stdio.h>
#include <string.h>

  char dest[] = "##########################";
  char source[] = "abcdefghijklmnopqrstuvwxyz";

void  main()
 {
     int  n;
     while (1)
     {
         puts("Enter the number of characters to copy (1-26)");
         scanf("%d", &n);
         if (n > 0 && n< 27)
             break;
     }
    printf("\nBefore strncpy destination = %s", dest);
    strncpy(dest, source, n);
     printf("\nAfter strncpy destination = %s\n", dest);
  }
Enter the number of characters to copy (1-26)
15
Before strncpy destination = ##########################
After strncpy destination = abcdefghijklmno###########

  • strncat(s1,s2,n) : concatenates first n characters of string s2 with string s1.
/* The strncat() function. */

  #include <stdio.h>
  #include <string.h>
  char str2[] = "abcdefghijklmnopqrstuvwxyz";
  main()
  {
     char str1[27];
     int n;
     for (n=1; n< 10; n++)
     {
         strcpy(str1, "");
         strncat(str1, str2, n);
         puts(str1);
     }
 }
The output:
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
  • strncmp(s1,s2,n): compares at most n characters of string s2 with string s1.

  • srdup(s): The library function strdup() is similar to strcpy(), except that strdup()
performs its own memory allocation for the destination string with a call     
to malloc().

/* The strdup() function. */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
  main()
  {
     char *dest;
     if ( (dest = strdup(source)) == NULL)
     {
         printf( "Error allocating memory.");
         exit(1);
     }
     printf("The destination = %s\n", dest);
     return(0);
 }

The destination = The source string.
ANALYSIS: In this program  strdup() allocates the appropriate memory for dest. It then makes a copy of the passed string, source. Line 18 prints the duplicated string.

No comments:

Post a Comment