其字母顺序排序在一个字符串数组的单个元素 [英] Sorting individual elements in a String Array by their alphabetical order
问题描述
我必须写一个程序,读取从文件中的字典单词的列表。
随后,每个字的字符放入字母顺序并存储在原始数组中为止。 (例如:蝙蝠侠将成为aabmnt)。
现在,这里是我迄今所做的:
I have to write a program that reads a list of dictionary words from a file. Subsequently, the characters of each word are put into alphabetical order and stored in the original array. (For example: Batman would become aabmnt). Now, here is what I've done so far:
public static String[] alphabeticalOrder(String[] s)
{
//
// Sort each individual string element by alphabetical order
//
for (int i = 0; i < s.length; i++)
{
String wordSt = s[i];
char[] word = wordSt.toCharArray();
Arrays.sort(word);
s[i] = new String(word);
}
return s;
}
在主通话很简单:的String [] = alphaOrder alphabeticalOrder(字典);
然而,每当我运行程序时,我收到了 NullPointerException异常
,我似乎无法找出原因。
However, whenever I run the program, I get a NullPointerException
and I can't seem to figure out why.
修改 S [I]
到 S [0]
让我跳过错误,但我需要转换String中的所有元素,而不仅仅是第一个。
Changing s[i]
to s[0]
made me skip the error, but I need to convert all elements in the String, not just the first.
这是怎么回事了?
推荐答案
这只能如果你的字符串数组有null元素发生,因为Zavior评论。
This can only happen if your string array has null elements, as Zavior commented.
更改code这样:
public static String[] alphabeticalOrder(String[] s)
{
//
// Sort each individual string element by alphabetical order
//
for (int i = 0; i < s.length; i++)
{
String wordSt = s[i];
if(wordSt == null) continue;
char[] word = wordSt.toCharArray();
Arrays.sort(word);
s[i] = new String(word);
}
return s;
}
这篇关于其字母顺序排序在一个字符串数组的单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!