Home > other >  If I try to print ch[0] or any random char of sorted char array after using Arrays.sort() it gives a
If I try to print ch[0] or any random char of sorted char array after using Arrays.sort() it gives a

Time:09-22

   class Solution
{
    public static String caseSort(String str)
    {
       char ch[]=new char[str.length()];
       char chy[]=new char[str.length()];
       int k=0,l=0;
       
       for(int i=0;i<str.length();i  )
       {
           if(str.charAt(i)>='a'&& str.charAt(i)<='z')
           ch[k  ]=str.charAt(i);
         
           else
           chy[l  ]=str.charAt(i);
       }
       Arrays.sort(ch);
       Arrays.sort(chy);
       
       int p=0,q=0; String stri="";
       for(int i=0;i<str.length();i  )
       {
          if(str.charAt(i)>='a'&& str.charAt(i)<='z')
          stri=stri ch[p  ];
        
          else
          stri=stri chy[q  ];
       }
       return stri;
    }
}

CodePudding user response:

Your Code is fine. The problem that is occurring is that you have defined your arrays with a length of the string so when you loop through and add characters in ch and chy arrays some places may be empty and when you sort this array those initial spaces will be at the start of the array and thus ch[0] will give a blank space.

CodePudding user response:

Before sorting ch and chy arrays it is needed to trim them to remove empty cells with '\0' characters, for example, using method Arrays::copyOf:

ch  = Arrays.copyOf(ch,  k);
chy = Arrays.copyOf(chy, l);
       
Arrays.sort(ch);
Arrays.sort(chy);

Or, p and q should be initialized with a certain shift instead of 0 - if ch contains k lower case letters, then int p = ch.length - k; and q = chy.length - l;

Also, it would be much better to use StringBuilder to concatenate the characters in the loop.

int p = ch.length - k, q = chy.length - l; 
StringBuilder sb = new StringBuilder(str.length());

for (int i = 0; i < str.length(); i  ) {
    if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
        sb.append(ch[p  ]);
    else
        sb.append(chy[q  ]);
}
return sb.toString();

Full code with more refactoring and test:

public static String caseSort(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }
    
    int n = str.length();
    
    char ch[]  = new char[n];
    char chy[] = new char[n];
    int k = 0, l = 0;
       
    for (char c : str.toCharArray()) {
        if (c >= 'a' && c <='z')
            ch [k  ] = c;
        else
            chy[l  ] = c;
    }
//  ch  = Arrays.copyOf(ch,  k);
//  chy = Arrays.copyOf(chy, l);
       
    Arrays.sort(ch);
    Arrays.sort(chy);

    int p = ch.length - k, q = chy.length - l; 
    StringBuilder sb = new StringBuilder(n);

    for (char c : str.toCharArray()) {
        sb.append(c >= 'a' && c <='z' ? ch[p  ] : chy[q  ]);
    }
    
    return sb.toString();
}

//  Test
System.out.println(caseSort("Hello,World!"));

Output:

!dell,HloorW
  • Related