编写一个程序,建立一个String型对象,其中包含你所选择的一段文本。从文本中提取每个单词并且按字母顺序将它们排序。显示排序后的单词列表。你可以使用所谓冒泡排序的简单排序方法。按升序对数组进行排序的过程如下:
口 从数组的第一个元素开始,相邻的两个元素进行比较(0和1、l和2、
等)。
口 如果出现一对元素的第一个数值大于第二个数值,就交换这两个几素。
口 对整个数组重复这个操作过程,直到没有可交换的元素对为止。现在,
元素就是按升序排列的。
/**
*将一段字符串文本中的每个单词提取出来后按照字母顺序排序
*/
public class Ex3
{
public static void main(String[] args)
{
String text = "Into the face of the young man who sat on the terrace " +
"of the Hotel Magnifique at Cannes crept a look of furtive " +
"shame, the shifty', 'hangdog look which announces that " +
"an Englishman is about to talk French." ;
/*
String[] result = text.split(" ");
for(int i = 0 ;i < result.length;i++)
{
System.out.println(result[i]);
}
*/
// Determine how many words there are.
// A word is a sequence of letters that may include a single quote character.
// Anything else is punctuation or spaces.
int count = 0 ; //Counts number of words
boolean isWord = false; //Indicates start of a word 就是一个标志
for(int i = 0;i
{
if(isWord)
{
if(Character.isLetter(text.charAt(i))||text.charAt(i) == '\'')//如果当前字符是字母或者单引号'
continue; //继续判断下一个
else
isWord = false; //否则将标志改为false
}
else if(Character.isLetter(text.charAt(i)))//标志为false的情况下 如果当前字符是字母
{
count++; //单词的数目加1
isWord = true; //将标志改为true 一个新单词的开始
}
}
//创建一个字符串数组来存放单词 长度为count
String[] words = new String[count];
int start = 0; //单词的开始位置
int wordIndex = 0; // Current vacant words array element
isWord = false;
for(int i = 0; i < text.length(); i++)
{
if(!isWord)
{
if(Character.isLetter(text.charAt(i)))
{
start = i;
isWord = true;
}
}
else
{
if(Character.isLetter(text.charAt(i))||text.charAt(i) == '\'')
continue;
else
{
isWord = false;
words[wordIndex] = text.substring(start,i);
wordIndex++;
}
}
}
// If the text ends with a letter, we will not have stored the last word
if(wordIndex < words.length)
words[wordIndex] = text.substring(start);
//排序
String temp = null;
boolean exchange = true; //声明我们交换了一对单词
while(exchange)
{
exchange = false;
for(int i = 1; i < words.length; i++)
{
if(words[i-1].compareTo(words[i])>0)
{
temp = words[i-1];
words[i-1 ] = words[i];
words[i ] = temp;
exchange = true;
}
}
}
// Display the sorted array of words:
for(int j = 0 ; j
System.out.print(words[j] + "\t");
}
};
最后修改于 2006-08-03 13:43
阅读(?)评论(0)