使用indexOf和substring以及compareTo交换名称
我无法理解如何使用 indexOf()
和 substring()
以及 compareTo()
方法来翻转人们的名字和姓氏数组中的名称。
I am having trouble understanding how to use the indexOf()
and substring()
and compareTo()
methods to flip people's first name with their last name in an array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您有以下内容:
您可以使用以下代码交换姓氏和名字:
现在可以使用字符串
compareTo
方法通过将一个名称与另一个名称进行比较来对名称进行排序,现在姓氏是字符串的开头。查看 api 此处 看看你是否能弄清楚。Let's say you have the following:
You can use the following code to swap the last name and first name:
The string
compareTo
method can now be used to sort the names by comparing one name against another, now that the last name is the start of the string. Have a look at the api here and see if you can figure it out.您可以使用 split 方法将名称分隔到 String 数组中,考虑到它们是用空格分隔的。
例如,让我们考虑一个名称:
此代码将在不同的行中打印每个名称(因为字符串是分隔的)
然后您可以使用 equals 方法比较分隔的名字和姓氏。
假设您有 2 个字符串数组,通过 split 方法获得,每个数组都有一个不同的人名。
Yo can use the split method to separate the names into a String array, considering that they are separed by a space.
For example, lets consider a name:
this code will print each name in a different line (as the String was separated)
Then you can compare the first and last name separated, using the equals method.
Let's suppose you have 2 array of Strings, obtained by split method and each one with one different Person name.
您可以使用正则表达式,特别是
String.replaceAll(String regex, String replacement)
对名字和姓氏重新排序。这将打印:
但是,如果您交换的唯一原因是因为您稍后想要对姓氏进行排序,那么您实际上根本不需要交换。只需将姓氏提取代码封装到辅助方法中(因此它是可测试的、可重用的等),然后在您的自定义
java.util.Comparator
为java.util.Arrays.sort
打印:
请注意,在这两个片段中,空格字符的 last 索引用于定义名字和姓氏之间的边界。
You can use regular expressions, specifically
String.replaceAll(String regex, String replacement)
to reorder the first name and last name.This prints:
However, if the only reason why you're swapping is because you later want to sort on last names, then you actually don't need to swap at all. Just encapsulate the last name extracting code into a helper method (so it's testable, reusable, etc), and then use it in your custom
java.util.Comparator
forjava.util.Arrays.sort
This prints:
Note that in both snippets, it's the last index of the space character that is used to define the boundary between the first and last name.