Saturday, 27 July 2013

STRING/CHARACTER ARRAY CONCEPTS IN C LANGUAGE

Introduction:

In our previous chapter (arrays), we studied that array is a collection of similar elements. These similar elements could be all ints, floats, doubles or any other data type. Array of chars are often called strings.

We are going to study character array in a separate chapter because operations that can performed on numbers, can not be applicable on characters. For example we can multiply two numbers but there is no sense to multiply two characters or strings.

Example:

main()
{
            char text[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’,’\0’ };
            int i=0;
            while(i<=5)
            {
                        printf(“%c”,text[i]);
                        i++;
            }
}

Explanation:
1)      In this program we handle character array in the same way as we handled int or float array. We have assigned Hello in a char array of size 6.
2)      Notice subtle difference during initialization of array. At the end ‘\0’ is assigned. The last element of character array should be nul character denoted by ‘\0’.
3)      In C, Strings are always terminated by nul character. It is great importance during handling of strings. It denotes the end mark of string.
4)      First character ‘H’ is stored in text[0], ‘e’ is stored in text[1] and so on. The last character ‘\0’ is stored in text[5].
5)       Loop is used to repeat printf() statement. Printf() is printing one character at a time.
6)      Remember nul (‘\0’) character is not a printable symbol.
7)      ASCII value of nul character is 0.

Example:

main()
{
            char text[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’,’\0’ };
            int i=0;
            while(text[i]!=’\0’)
            {
                        printf(“%c”,text[i]);
                        i++;
            }
}

Explanation:
1)      Notice the difference in loop condition. This time condition checks for nul character in text[i]. Until nul character is found in text[i], loop continues.
2)      This way of handling gives an ease to the programmer and no need to care about the length of the string.

Example:
main()
{
            char text[6] = “Hello”;
            int i=0;
            while(text[i]!=’\0’)
            {
                        printf(“%c”,text[i]);
                        i++;
            }
}

Explanation:
1)      Notice the way of initializing array. Instead of writing each character in single quotes and separating with commas, this convention is convenient to use.
2)      Another important point to note is- there is no need to write nul character at the end in this convention, compiler automatically appends nul character at the end.
3)      Rest of the things are same

Example:
main()
{
            char text[6] = “Hello”;
printf(“%s”,&text[0]);
}

Explanation:
1)      Here is another program telling you the use of format specifier %s. This is used only for strings.
2)      Observe that in printf we write &text[0] and not text[0]. This means with %s format specifier one should always use address of first block of array.
3)      You can write text in place of &text[0], both have the same meaning.
4)      When you pass &text[0] or simply text, it means printing should strat from text[0] and end when nul character arrives.

Example:
main()
{
            char text[ ] = “Hello”;
printf(“%s”,&text[0]);
}

Explanation:
1)      You can also leave array size blank as you are assigning values to array during declaration.

Example:
main()
{
            char text[20];
            printf(“Enter your name”);
            scanf(“%s”,&text[0]);
printf(“hi, %s”,&text[0]);
}

Explanation:
1)      In this program, user can input his name as we used scanf().
2)      Notice %s is used in scanf for string input. Again remember, if you are using %s in printf or scanf always pass address of the first block of array.
3)      Run this code to understand the capabilities of scanf().
4)      If you input Amir, it will get stored in the array and nul character is automatically appended by compiler.
5)      If you input Amir Khan, only the first word of the input string will be stored in character array and nul is automatically appended.
6)      Scanf() is not capable to input multiword string. The solution to this problem is a function gets()


EXAMPLE:
main()
{
            char text[20];
            printf(“Enter your name”);
            gets(&text[0]);
printf(“hi, %s”,&text[0]);  //or puts(&text[0]);
}

Explanation:
1)      No need to mention format specifier in function gets() as it is dedicated only for string input.
2)      gets() is declared in stdio.h header file.
3)      Function gets() can input only one string at a time.
4)      As gets() can be used for input, function puts() can be used for output in place of printf().
5)      Printf can print multiple strings in a single statement, on the other hand puts can only output single string.

Example: Program to calculate length of string
main()
{
            char text[20];
            int len=0;
            printf(“Enter a string ”);
            scanf(“%s”,&text[0]);
            while(text[len]!=’\0’)
                        len++;
printf(“Length of string:  %s is %d”,&text[0],len);
}

Explanation:
1)      If you input Sachin length will be 6. If you input Saurabh length will be 7.
2)      To calculate length of a given string, we take a variable len. len is initialized with 0. len is now incremented till text[len] becomes nul. Since len is now containing index of that block which contains nul. The value of len is length of the string excluding nul character.
3)      No need to decrease len by 1 to show length at last, as indexing starts from 0.

Built-in function for String manipulation:

There are several predefined functions to manipulate strings. These functions are declared in string.h. We are discussing few of them:

Function name:  strlen()
Usage:
main()
{
            int len;
            char str[20];
            printf(“Enter a string”);
            gets(str);
            len=strlen(str);
            printf(“Length is %d”,len);
}


Function name:  strrev()
Usage:
main()
{
            char str[20];
            printf(“Enter a string”);
            gets(str);
            printf(“You entered %s”,str);
strrev(str);
            printf(“Reverse is %s”, str);
}

Function name: strlwr()
Usage:
main()
{
            char str[20];
            printf(“Enter a string”);
            gets(str);  //sample input is SCA
            strlwr(str);
            printf(“String in lower case is %s”,str);  //sample output is sca
}

Function name:  strupr()
Usage:
main()
{
            char str[20];
            printf(“Enter a string”);
            gets(str);  //sample input is sca
            strupr(str);
            printf(“String in upper case is %s”,str);  //sample output is SCA
}

Function name:  strcpy()
Usage:
main()
{
            char str1[20], str2[20];
            printf(“Enter a string”);
            gets(str1);  //sample input is Computer
            strcpy(str2,str1);
            printf(“String1=%s and String2 = %s”,str1,str2); 
}
Output
String1=Computer and String2=Computer

Function name:  strcat()
Usage:
main()
{
            char str1[20], str2[40];
            printf(“Enter two strings”);
            gets(str1);  //sample input is Computer
            gets(str2); //sample input is Education
            strcat(str2,str1);
            printf(“String1=%s and String2 = %s”,str1,str2); 
}
Output
String1=Computer and String2=ComputerEducation

Function name:  strcmp()
Usage:
main()
{
            int r;
            char str1[20], str2[20], str3[20];
            printf(“Enter three strings”);
            gets(str1);  //sample input is Hello
            gets(str2); //sample input is Hello
            gets(str3); //sample input is hello
            r=strcmp(str2,str1);
            printf(“%d”,r);  //output is 0 
            r=strcmp(str1,str3);
            printf(“%d”,r); //Output is -32
}

Two Dimension character array:
This is similar to two dimension array that we studied in previous chapter.

main()
{
            int i;
            char str[5][10];
            printf(“Enter 5 strings”);

            for(i=0;i<5;i++)
                        gets(str[i]); 

            for(i=0;i<5;i++)
                        printf(“\nString %d = %s ”,i+1,str[i]); 
}
Explanation:
1)      A two dimensional character array can store multiple strings. According to our example we can store 5 strings each can contain 10 characters.
2)      Notice function gets() we passed str[i] which is equivalent to &str[i][0]. Same is the case in printf().

No comments:

Post a Comment