Thursday, 24 August 2017

REVERSING ONLY CHARACTERS OF STRING

Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’to ‘Z’),
reverse the string in a way that special characters are not affected.

E.g.:
Input:
str = "a,b$c"

Output:
str = "c,b$a"

Note that $ and, are not moved anywhere.
Only sub-sequence "abc" is reversed

Input:
str = "Ab,c,de!$"

Output:
str = "ed,c,bA!$"
 
CODE: 

#include<stdio.h>
#include<string.h>
void main()
{
    char a[50],temp[50],r[50];
    scanf("%s",a);
    int i,j,k=0,l;
    l=strlen(a);
    for(i=0;a[i]!='\0';i++)
    {
        if(a[i]>=65&&a[i]<=90||a[i]>=97&&a[i]<=122)
            {
                temp[k++]=a[i];
            }
    }
    j=0;
    for(i=k-1;i>=0;i--)
    {
        r[j++]=temp[i];   
    }   
    j=0;
    for(i=0;a[i]!='\0';i++)
    {
        if(a[i]>=65&&a[i]<=90||a[i]>=97&&a[i]<=122)
            {
                a[i]=r[j++];
            }
    }
    for(i=0;i<l;i++)
    {
        printf("%c",a[i]);
    }
}

No comments:

Post a Comment