Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a code to alphabetically sort a string. I have to find magic name, i.e. alphabetically sorted string. It is as under:
import java.util.*;
import java.io.*;
import java.lang.*;
public class magicnum{
    
    public static void main(String args[]) throws java.util.NoSuchElementException
{
    Scanner sc=new Scanner(System.in);
   
     System.out.println("Enter a string value: ");
      String st = sc.nextLine();
     int j = 0;
      char temp = 0;
      char[] character = st.toCharArray();
      for(int i=0; i < character.length; i++) {
         for(j=0; j < character.length; j++) {
            if(character[j] > character[i]) {
               temp = character[i];
               character[i] = character[j];
               character[j] = temp;
            }
         }
      }
      System.out.println("After Sorting:");
      
        String str1=new String(character);
System.out.println("Magic name is:"+str1);
    
      

    
}
}

Is there any way in which the same code can be written without using toCharArray()?

What I have tried:

import java.util.*;
import java.io.*;
import java.lang.*;
public class magicnum{
    
    public static void main(String args[]) throws java.util.NoSuchElementException
{
    Scanner sc=new Scanner(System.in);
   
     System.out.println("Enter a string value: ");
      String st = sc.nextLine();
     int j = 0;
      char temp = 0;
      char[] character = st.toCharArray();
      for(int i=0; i < character.length; i++) {
         for(j=0; j < character.length; j++) {
            if(character[j] > character[i]) {
               temp = character[i];
               character[i] = character[j];
               character[j] = temp;
            }
         }
      }
      System.out.println("After Sorting:");
      
        String str1=new String(character);
System.out.println("Magic name is:"+str1);
    
      

    
}
}
Posted
Updated 2-Feb-23 21:55pm

1 solution

Quote:
Is there any way in which the same code can be written without using toCharArray()?
Yes, use a StringBuilder (Java Platform SE 7 )[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900