【问题标题】:Java Sorting alphabet and get position number [closed]Java对字母进行排序并获取位置编号[关闭]
【发布时间】:2014-01-08 05:14:59
【问题描述】:

我用输出“act”编写了以下代码,我想将其转换为数字“a”为 1,“c”为 2,“t”为 3。

public static void main(String[] args) {

    String s1 = "cat";
    char[] arr;
    arr = s1.toCharArray();
    Arrays.sort(arr);
    s1 = new String(arr);
    System.out.println(s1);

}

输出

act

【问题讨论】:

  • 不是很清楚你在问什么。请尝试发布具体问题。
  • 你理解能力差那么=D
  • 来吧,帮我们帮你!
  • 我认为这里的问题是提供的信息不多。
  • 我本可以猜到问题是什么,但在发布答案之前问不是更好吗?只是为了确定。

标签: java sorting


【解决方案1】:

对数组进行排序后,您可以简单地遍历每个数组元素并打印出每个元素的索引。

for(int i = 0; i < arr.length; i++) {
    System.out.println(arr[i] + " is at the position " + (i + 1));
}

请注意,您需要使用i + 1,因为数组具有基于0的索引。

【讨论】:

    【解决方案2】:

    使用 Ascii 值

    public class Ssort 
    {
        public static void main(String[] args) 
        {
            Scanner s=new Scanner(System.in);
            String s1=s.nextLine();
            String s2=s1.toLowerCase();
            char []a=s2.toCharArray();
            int h,g = 0,l=0;
            int b=(int)a[0];
            System.out.println();
            for(int k=0;k<a.length;k++)
            {
                for(h=1+k;h<a.length;h++)
                {
                    if(b>(int)a[h])
                    {   
                        b=a[h];
                        char temp=a[h];
                        a[h]=a[k];
                        a[k]=temp;
                    }
    
                }
            if(l<a.length-1)
            {
                    b=a[++l];
            }
            }
    
            for(int j=0;j<a.length;j++)
            {
                System.out.print(a[j]);
            }
        }
    
    }
    

    使用字母排序

    public class Hi1 {
    
    
        public static void main(String[] args)
        {
            String s1,s3;
            java.lang.String s2;
            int i,j;
            Scanner s=new Scanner(System.in);
            s1=s.nextLine();
            s2="abcdefghijklmnopqrstuvwxyz";
            s3=s1.toLowerCase();
            char [] c=s3.toCharArray();
            char [] c1=s2.toCharArray();
            for(i=0;i<c1.length;i++)
            {
                for(j=0;j<c.length;j++)
                {
                    if(c1[i]==c[j])
                    {
                        System.out.print(c[j]);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            //System.out.println(c[0]);
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      试试,

      String s1 = "act";
      for(char c :s1.toCharArray())
           System.out.println(s1.indexOf(c)+1);
      

      【讨论】:

        猜你喜欢
        • 2014-10-25
        • 2013-10-28
        • 1970-01-01
        • 2021-07-30
        • 2020-04-18
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多