Skill Rack
Daily Challenge Solution
Date : 05/04/2019
ProgramID- 8469
Inplace Swap First Half and Second Half
The program must swap the first half and second half in the string str passed as the argument to the function swapFirstHalfSecondHalf.
Note: The length of the string str is always even.
Example Input/Output 1:
Input:
capslock
Output:
lockcaps
Explanation:
The first half of the string str is "caps".
The second half of the string str is "lock".
After swapping, the str becomes "lockcaps".
Example Input/Output 2:
Input:
keymap
Output:
mapkey
Solution:
-------------------------------------------------------------------------------------
void swapFirstHalfSecondHalf(char *str)
{
int l,i;
char *str1,*str2;
str1=(char *)malloc(50);
str2=(char *)malloc(50);
l=strlen(str);
int j=0;
for(i=0;i<(l/2);i++)
{
str1[j]=str[i];
j++;
}
j=0;
for(i=(l/2);i<l;i++)
{
str2[j]=str[i];
j++;
}
strcat(str2, str1);
for(int k=0;k<l;k++)
{
str[k]=str2[k];
}
}
-------------------------------------------------------------------------------------
No comments:
Post a Comment