[英]Sort a string in alphabetical order without arrays in java
What I need to do is take a string that has random letters and take the letters and put them in alphabetical order. 我需要做的是取一个包含随机字母的字符串,然后按字母顺序排列字母。 For example, lidfj, would be;
例如,lidfj将是; dfijl.
dfijl。
What I am having trouble figuring out is how I should start the code. 我要弄清楚的是如何启动代码。 I know that I may need to use compare to, since I am not allowed to use arrays, but I'm not sure if that would be the best approach.
我知道我可能需要使用compare to,因为不允许使用数组,但是我不确定这是否是最好的方法。 And I'm not sure how I would start that either.
我也不知道该如何开始。
Thanks in advance. 提前致谢。
Edit: I think I'm done for the night, since I can't seem to think of anything else. 编辑:我想我已经晚上住完了,因为我似乎再也没有想到其他任何事情了。
public class PP426 {
public static String alphabetize (String input) {
String sorted = ";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if () {
sorted += character;
}
}
return sorted;
}
public static void main(String[] args) {
System.out.println(alphabetize("iunaselfksdf"));
}
}
From your questions and comments, seems that it is a homework assignment, for which you are allowed to use only String class for sorting (it is obviously not efficient but... well... it is a homework anyway). 从您的问题和评论看来,这似乎是一项家庭作业,只允许您使用String类进行排序(显然效率不高,但是...好吧...仍然是一项家庭作业)。
Here I assume you already have idea on how to do sorting (eg bubble sort) with array. 在这里,我假设您已经对如何使用数组进行排序(例如冒泡排序)有所了解。 If not, search for the simplest sorting algorithm like insertion sort and learn it.
如果不是,请搜索最简单的排序算法(例如插入排序)并进行学习。
If you know how to sort with an array, you can simply translate your logic to use String's methods. 如果您知道如何对数组进行排序,则可以简单地转换逻辑以使用String的方法。
For example: 例如:
yourString.charAt(i)
yourString.charAt(i)
yourString = yourString.substring(0, i) + charToSet + yourString.substring(i+1)
yourString = yourString.substring(0, i) + charToSet + yourString.substring(i+1)
yourString += charToSet
yourString += charToSet
If you don't even have knowledge in sorting, here is one method that works which involves only String: 如果您甚至不了解排序,那么以下一种有效的方法仅涉及String:
I am not going to give you actual code. 我不会给您实际的代码。 Learn it by yourself:
自己学习:
for currentChar in 'a' to 'z'
loop through each char in inputString
if you encounter any char = currentChar then
append that character to resultString
end if
end loop
end for
resultString contains the result you need
Use a for
loop and String.charAt()
to traverse the string. 使用
for
循环和String.charAt()
遍历字符串。 Use a StringBuilder
(for efficiency, concatenating Strings works as well but is meh performance wise) to assemble the letters in the order. 使用
StringBuilder
(为了提高效率,连接字符串也可以,但从性能上考虑)可以按顺序组装字母。 WIth this knowledge, now implement you preferred sorting algorithm (which, I guess, is part of the excersise, so I won't do it here ;) ) 有了这些知识,现在就可以为您实现首选的排序算法(我想这是练习的一部分,因此在这里我不会做;))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.