Why this code for anagram is not giving correct result only for ravi & vira?

  c++, c++14

In this program i am trying to sort the string by their ASCII values by taking them as a integer. And then sort them in ascending order and check if they have the same set of elements

#include<iostream>
#include<string.h>
using namespace std;

int len(int a[]){
    int l=0;
    for(int i=0; a[i]!='{$content}'; i++)
        l++;
    return l;    
}
int len_str(string a){
    int l=0;
    for(int i=0; a[i]!='{$content}'; i++)
        l++;
    return l;    
}
void asc_order(int a[]){
    int n=len(a), temp=0;
    for(int i=0; i<n ; i++)
        for(int j=0; j<n; j++)
            if(a[i]<a[j]){
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
}

int main(){
    system("cls");
    string str1, str2;
    cout<<"Enter the first string  : ";
    getline(cin, str1);
    cout<<"Enter the second string : ";
    getline(cin, str2);
    string res = "YES";
    if(len_str(str1)==len_str(str2)){
        int n = len_str(str1);
        int ch1[n], ch2[n];
        for(int i=0; i<n; i++){
            ch1[i] = str1[i];
            ch2[i] = str2[i];
        }
        asc_order(ch1);
        asc_order(ch2);
        for(int i=0; i<n; i++)
            if(ch1[i]!=ch2[i])
                res = "NO";
    }
    else
        res = "NO"; 
    cout<<res;
}

It gives NO as the res when str1 and str2 are ravi and vira respectively.

Source: Windows Questions C++

LEAVE A COMMENT