Home > Java > javaTutorial > body text

How to sort input words by first letter in java

王林
Release: 2019-11-25 15:14:21
forward
8569 people have browsed it

How to sort input words by first letter in java

Question:

Sort the given series of English words by first letter and output the sorted results.

Such a method in StringcompareToIgnoreCase()It ignores case and compares the order of two words in the dictionary. By using this method, this problem can be easily solved.

Related learning video recommendations: java video

The following is the demo code:

import java.util.Scanner;
/*
 * 请对给出的一系列英文单词按首字母进行排序,并输出排序后的结果。
		输入说明:数字N,表明单词数,接下来是N个英文单词;
		输出说明:按字母序的排序结果。
		输入样例:6
		Apple  banana  Zebra  Tuesday  moon  CAN
		输出样例:Apple
		  banana
		CAN  
		moon  
		Tuesday  
		Zebra
 */
public class Sort {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("请输入单词的个数:");
		int num = input.nextInt();
		String[] strArr = new String[num];
		System.out.println("请输入单词:");
		for(int i = 0;i < strArr.length;i++) {
			strArr[i] = input.next();
		}//将键盘输入的单词输入到String数组中
		wordSort(strArr);
	}
	public static void wordSort(String[] strArr) {
	//比较单词字典顺序  用冒泡排序法比较
		for(int i = strArr.length - 1;i > 0;i--) {
			for(int j = 0;j < i;j++) {  
				if(strArr[j].compareToIgnoreCase(strArr[j + 1]) > 0) {
					String temp = strArr[j];
					strArr[j] = strArr[j + 1];
					strArr[j + 1] = temp;
				}
			}
		}
	for(String i : strArr) {
		System.out.println(i);
	}
}
}
Copy after login

There are many ways to solve this problem, not all of them here. Everyone introduces, welcome everyone to come to the PHP Chinese website to learn together.

For more related articles, please visit: Getting Started with Java

The above is the detailed content of How to sort input words by first letter in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!