如何翻转字符串中的两个单词,Java
假设我有一个名为 x 的字符串 =“Hello world”。我想以某种方式做到这一点,以便它翻转这两个词并显示“world Hello”。我不太擅长循环或数组,显然是一个初学者。我可以通过分割字符串来实现这一点吗?如果是这样,怎么办?如果没有,我该怎么做?帮助将不胜感激,谢谢!
So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
1)在空间上将字符串拆分为
String
数组。2) 使用与数组相反的单词顺序创建新字符串。
使用 StringBuilder 而不是串联的奖励点。
1) split string into
String
array on space.2) Create new string with words in reverse order from array.
Bonus points for using a
StringBuilder
instead of concatenation.如果你愿意,你也可以爆炸你的绳子:
还有很多其他方法可以做到这一点。请注意大小写。您可以在 if 语句中使用 .toUpperCase() ,然后使匹配的条件大写,但保留结果的原始大写等。
If you want, you can explode your string as well:
There are many other ways you can do it too. Be careful for capitalization. You can use .toUpperCase() in your if statements and then make your matching conditionals uppercase, but leave the results with their original capitalization, etc.
解决方案如下:
上述解决方案是我为 Google Code Jam 编写的,也发布在此处:反向词 - GCJ 2010
Here's the solution:
The above solution was coded by me, for Google Code Jam and is also blogged here: Reverse Words - GCJ 2010
只需使用这个方法,调用它并传递你想要拆分的字符串
Just use this method, call it and pass the string that you want to split out
根据您的具体要求,您可能需要分割其他形式的空白(制表符、多个空格等):
如果您想变得更复杂,请参阅模式文档 http://docs.oracle.com/javase/6/docs/api/java/util/regex /模式.html
Depending on your exact requirements, you may want to split on other forms of whitespace (tabs, multiple spaces, etc.):
If you want to get more complex see the docs for Pattern http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
尝试如下操作:
输出:
Try something as follows:
Output:
太多了?
Too much?