This function copies the last n characters of a string to another
string. For example, suppose string1 contains "Computer Science"
,then copying last 5 characters of string1 will make string to contain
"ience".
#include<stdio.h>
#include<string.h>
void strncopylast(char *str1,char *str2,int n)
{ int i;
int l=strlen(str1);
if(n>l)
{
printf("\nCan't extract more characters from a smaller string.\n");
exit(1);
}
for(i=0;i<l-n;i++)
str1++;
for(i=l-n;i<l;i++)
{
*str2=*str1;
str1++;
str2++;
}
*str2='\0';
}
int main()
{
char str1[]="Computer Science & Engineering";
char str2[50];
int n;
printf("\nEnter number of character to be copied?");
scanf("%d",&n);
strncopylast(str1,str2,n);
printf("str2=");
puts(str2);
return 0;
}
#include<string.h>
void strncopylast(char *str1,char *str2,int n)
{ int i;
int l=strlen(str1);
if(n>l)
{
printf("\nCan't extract more characters from a smaller string.\n");
exit(1);
}
for(i=0;i<l-n;i++)
str1++;
for(i=l-n;i<l;i++)
{
*str2=*str1;
str1++;
str2++;
}
*str2='\0';
}
int main()
{
char str1[]="Computer Science & Engineering";
char str2[50];
int n;
printf("\nEnter number of character to be copied?");
scanf("%d",&n);
strncopylast(str1,str2,n);
printf("str2=");
puts(str2);
return 0;
}
Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.
No comments:
Post a Comment