Wednesday, July 20, 2011

Program to accept a string and print the rightmost 'n' characters using function {Version 1}

/*Serial No.97     [swami72.cpp]*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
char *rightsub(char *,int n);
void main()
{
char s1[20],s2[20],ch,*s;
int n;
clrscr();
printf("enter the string s1:");
gets(s1);
printf("enter the no of characters to extract=");
scanf("%d",&n);
s=rightsub(s1,n);
printf("\nright sub string: %s",s);
free(s);
getch();
}
char *rightsub(char *str,int n)
    {
    char *t=(char *)malloc(n+1);
    int l=strlen(str);
    char *s=str+(l-n);
    int i=0;
    while(i<n)
        {
        t[i]=*s;
        s++;
        i++;
        }
    t[i]='\0';
    return t;
    }

No comments:

Post a Comment

If you have any doubt, feel free to ask...