Showing posts with label Strings. Show all posts
Showing posts with label Strings. Show all posts

Tuesday, 12 February 2013

C Programming: Strings

iA string is a sequence of characters( Array of character)  that is treated as a single data item. Any group of characters (except double quote sign) defined between double quotation marks is a string constant. Example:
“All is Well”
If you want to include a double quote in the string to be printed, then you may use it with a back slash as shown below:
“\”All is Well, \” said Amir Khan.”
Declaring String Variables
C does not support strings as a data type as C++, JAVA etc. However, it allows us to represent strings as character arrays. In C, therefore, a string variable is any valid C variable name and is always declared as an array of characters. The general syntax of declaration of string is:
char string_name [ size];

The size determines the number of characters in the string_name. Example: char city[20]; When the compiler assigns a character string to a character array, it automatically supplies a null character(‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

Initializing string variable

C permits a character array to be initialized in either of the following two forms:
  1: char city[10] = "Kathmandu";
  2: char city[10] = {'K','a','t','h','m','a','n','d','u','\0'};

The reason that city had to be 10 elements long is that the string Kathmandu contains 9 characters and one element space is provided for the null terminator.

Reading String from user

The familiar input function scanf can be used with %s format specification to read in a string of characters. Example:
char address[10];
scanf("%s",address);
 

Note that there is no amp percent(&) before address , it is because address itself represents the first address of string. The problem with scanf with %s  is that it terminates its input on the first white space it finds. For example if I enter NEW YORK, then it only takes NEW as input and neglects YORK. To avoid this you can write following code to read input
  1: char address[10];
  2: scanf("%[^\n]", address];
  3: gets(address)

You can either use scanf with %[^\n] as format specification or use gets(string_name).

String operations (length, compare, copy, concatenate) without including string.h using C

In C, string.h includes various build in functions for string operations. The main operations are
1. Length of the string (strlen)
The syntax of strlen is :

strlen(string);
It calculates the length of the string and returns its length. For example:

#include<string.h>
string = "Mumbai";
printf("Length = %d",strlen(string));

The above code displays 5, because Mumbai consists of 5 characters. Note: it does not count null character.

2. Joining two strings (strcat)

The syntax of strcat is
strcat(string1,string2);
Now it removes the null character from string1 and joins the first character of string2 at that position. Now string1 consists of both string1 and string2 in joined form. Example:

#include<string.h>
char string1[] = "Anti";
char string2[] = "Particle";
strcat(string1,string2);
printf("%s",string1); //display AntiParticle

3. Comparing two strings(strcmp)

The syntax of strcmp is
strcmp(string1,string2);
It returns 0 if string1 is same as string2 and returns 1 if they are not same. Example:

#include<string.h>
char string1 = "Nepal";
char string2 = "Srilanka";
if(strcmp(string1,string2)==0){
printf("They are equal");
}else{
printf("They are not equal"); //this is executed
} 

4. Copying one string to another (strcpy)

The syntax of strcpy is

strcpy(destination_string, source_string);

It copies the content of source_string to destination_string. Example:

#include<string.h>
char source[] = "Hello";
char destination[10]; //uninitialized
strcpy(destination,source);
printf("%s",destination); //prints Hello 
These are some of the functions in string.h for string operation. To use these functions you must include header file <string.h>. But we can make our own functions to perform above task without including string,h. Here is the complete source code that has own functions find_length (like strlen) to find length, join_strings( like strcat) for joining strings, compare_strings(like strcmp) for comparing two strings and copy_string(like strcpy) to copy one string from another. Observer carefully the code, if you are beginner, you will learn a lot of things about string operation.

Source Code


///fundamental string operation, lenth, concatenation, compare and copy strings without string.h
#include<stdio.h>
#include<stdlib.h>
int find_length(char string[]){
int len = 0,i;
for(i = 0; string[i]!='\0'; i++){
len++;
}
return len;
}
void join_strings(char string1[], char string2[]){
int i, len1, len2;
len1 = find_length(string1);
len2 = find_length(string2);
for(i = len1; i < len1+len2; i++){
string1[i] = string2[i-len1];
}
string1[i] = '\0'; //adding null character at the end of input
}
/*returns 0 if thery are same otherwise returns 1*/
int compare_strings(char string1[], char string2[]){
int len1, len2, i, count = 0;
len1 = find_length(string1);
len2 = find_length(string2);
if(len1!=len2)
return 1;
for(i = 0; i < len1; i++){
if(string1[i] == string2[i])
count++;
}
if(count == len1)
return 0;
return 1;
}
void copy_string(char destination[], char source[]){
int len,i;
len = find_length(source);
for(i = 0; i < len; i++){
destination[i] = source[i];
}
destination[i] = '\0';
}
int main(){
char string1[20], string2[20]; //string variables declaration with size 20
int choice;
while(1){
printf("\n1. Find Length \n2. Concatenate \n3. Compare \n4. Copy \n5. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter the string: ");
scanf("%s",string1);
printf("The length of string is %d", find_length(string1));
break;
case 2:
printf("Enter two strings: ");
scanf("%s%s",string1,string2);
join_strings(string1,string2);
printf("The concatenated string is %s", string1);
break;
case 3:
printf("Enter two strings: ");
scanf("%s%s",string1,string2);
if(compare_strings(string1,string2)==0){
printf("They are equal");
}else{
printf("They are not equal");
}
break;
case 4:
printf("Enter a string: ");
scanf("%s",string1);
printf("String1 = %s\n");
printf("After copying string1 to string 2\n");
copy_string(string2,string1);
printf("String2 = %s",string2);
break;
case 5:
exit(0);
}
}
return 0;
}

Output


string

C Programming: Dynamic Memory Allocation (DMA)

C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many language permit a programmer to specify an array’s size at run time. Such languages have the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation.
Allocating a Block of Memory
A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. General syntax is
ptr = (cast_type*) malloc (byte-size);

ptr is a pointer of type cast_type. The malloc returns a pointer (of cast_type) to an area of memory with size byte_size. Example:
x = (int*) malloc (100*sizeof(int));

On successful execution of this statement, a memory space equivalent to “100 times the size of and int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type of int.

Releasing the used space

When we no longer need the data we stored in a block of memory, and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function:
free(ptr);

Sorting strings alphabetically using C

Source Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reorder(int n, char *x[]);
int main(){
    int i , no_string;
    char *x[10];
    printf("Enter the no of strings: ");
    scanf("%d",&no_string);
    printf("Enter the strings: \n");
    for(i = 0; i < no_string; i++){
        x[i] = (char*) malloc (12*sizeof(char));
        printf("string %d: ",i+1);
        scanf("%s", x[i]);
    }
    printf("The sorted strings are: ");
    reorder(i,x);
    for(i = 0; i < no_string; i++){
        printf("\nstring %d: %s", i+1, x[i]);
    }
    return 0;
}
void reorder(int n, char *x[]){
    char *temp;
    int i,item;
    for(item = 0; item < n-1; ++item){
        for(i = item+1; i < n; ++i){
            if(strcmp(x[item],x[i]) > 0){
                temp = x[item];
                x[item] = x[i];
                x[i] = temp;
            }
        }
    }
    return;
}

Output


string_sort

Tuesday, 5 February 2013

Find address of char, string, integer

====List Of Defination Clickk Me========


#include<stdio.h>
#include<conio.h>
 main()
  {
   char *chp,*sp;
   int i;
   char ch,s[10];
   int *ip;
   clrscr();
   printf("Enter a char:");
   scanf("%c",ch);
   printf("Enter a string:");
   scanf("%s",s);
   printf("Enter a integer:");
   scanf("%d",&i);
   chp=&ch;
   sp=s;
   ip=&i;
   printf("\nchar\tadd\tstring\t\tstringadd\tint\tint add\n");
   printf("%c\t%u\t%s\t\t%u\t\t%d\t%u",ch,&chp,s,&s,i,&i);
   printf("\nchar pointer value is:%u",chp);
   printf("\nstring pointer value is:%u",sp);
   printf("\nint pointer value is:%u",ip);
   getch();
  }


====List Of Defination Clickk Me========

Example of Using Strings in C

# include<stdio.h>
# include<conio.h>
# include<string.h>

void main()
{
char *a;
printf("Enter your name=");
gets(a);
printf("%s",a);
getch();

Monday, 4 February 2013

ARRANGE THE ELEMENTS IN ARRAY IN DESSENDING ORDER

main()
{
int a[100],i,n,j,search,temp;
printf("\n how many no's in array");
scanf("%d",&n);
printf("\n enter %d elements in array",n);
for(i=0;i
scanf("%d",&a[i]);
for(i=0;i
{
for(j=i+1;j
{
if(a[i]
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
printf("%4d",a[i]);
}
getch();
}

Wednesday, 30 January 2013

WAP TO FIND STRING WITHIN A STRING


void main ()
{
char *k="Borland International", *g, *p;
clrscr ();
printf ("Enter string to find: ");
gets (g);
p=strstr(k,g);
printf ("%s",p);
getch ();
}

WAP TO PRINT NAME AND DISPLAY ON SCREEN


void main ()
{
char name [15];
clrscr ();
printf ("Enter your name: ");
gets (name);
printf ("\name is: %s",name);
getch ();
}


Output:
==============
Hi

nameis:Hi

WAP TO PRINT ASCII CODE FROM 0 TO 255


void main ()
{
int i=0,count=0;
clrscr ();
for(i=0;i<=255;i++)
{
if (count>24)
{count=0;getch();}
else
{printf("%d=%c\n",i,i);
count++;}
}
getch ();
}


Output:
==========

WAP TO CONCATENATE TWO STRINGS


void main ()
{
char *str,*str1;
clrscr ();
printf("Enter your name: ");
gets (str);
str1="jeet";
strcat(str,str1);
printf("\n %s",str);
getch ();
}