Java编程——输入一段字符串,然后按字母顺序输出。并查询某个字母在这段字符串中出现的次数

2024-11-12 20:29:32
推荐回答(3个)
回答1:

import java.util.Arrays;
import java.util.Scanner;
class Method{
public void _Sort(String str){
char[] ch=new char[str.length()];
for(int i=0;ich[i]=(char)str.charAt(i);
Arrays.sort(ch);
for(int j=0;jSystem.out.print(ch[j]);
}
public int _Search(String str,char c){
int count=0;
char[] ch=new char[str.length()];
for(int i=0;ich[i]=(char)str.charAt(i);
for(int i=0;iif(ch[i]==c)
count++;
}
return count;
}
}
public class Test_01{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("请给定字符串:");
String s=input.nextLine();
System.out.print("请给定需要检查的字母:");
String ss=input.next();
char c=ss.charAt(0);
Method mh=new Method();
System.out.println("排序前:"+s);
System.out.print("排序后:");
mh._Sort(s);
System.out.println();
System.out.println(c+"字母共出现了"+mh._Search(s,c)+"次");
}
}

回答2:

import java.util.Scanner;
import java.util.Arrays;
class MyTest
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str = in.next();
char[] c = str.toCharArray();
Arrays.sort(c);
str = String.valueOf(c);
System.out.println(str);
System.out.println("输入你要查询的字符:");
String s = in.next();
int i = 0;
int index = 0;
while((index = str.indexOf(s, index + 1)) != -1)
{
i++;
}
System.out.println("字符" + s + "出现" + i + "次。");
}
}

回答3:

排序
String str = "AdaaaqweafgGddddynMmmCdddXZ";
byte[] bytes = str.getBytes();
Arrays.sort(bytes);
for(byte b:bytes){
System.out.print((char)b);
}

统计
Map map = new HashMap();
for(int i=0, len=str.length(); ichar ch = str.charAt(i);
Integer n = map.get(ch);
map.put(ch, n==null ? 1 : n+1);
}
System.out.println(map);