英文:
Reverse a string word by word except the last letter of each word
问题
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
char[] ch = s.toCharArray();
System.out.println(ch.length);
int pos = 0;
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ' ') {
for (int j = i; j >= pos; j--) {
System.out.print(ch[j]);
}
pos = i + 1;
}
}
}
}
英文:
I'd like to reverse a string word by word except the last letter of each word.
For example: "Hello how are you"
-> lleHo ohw rae oyu
but I am getting output as: olleH woh era uoy
I'm not able to fix the last letter of each word.
This is my Java code for the above output:
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
for(int j=i;j>=pos;j--)
{
System.out.print(ch[j]);
}
pos=i+1;
}
}
}
}
答案1
得分: 1
以下是解决问题的解决方案:
public class Main {
public static void main(String[] args) {
//调用reverseSentence方法
reverseSentence("Hello how are you");
}
public static void reverseSentence(String sentence) {
//将多个空格替换为单个空格
sentence = sentence.replaceAll("[ ]{2,}", " ");
//分割字符串并存储在数组中
String[] arr = sentence.split(" ");
StringBuilder finalString = new StringBuilder();
//使用forEach循环遍历数组
for (String str : arr) {
//创建单词的子字符串,去掉最后一个字母
String s = str.substring(0, str.length() - 1);
//创建StringBuilder对象并反转字符串
StringBuilder sb = new StringBuilder(s);
//反转字符串并再次添加单词的最后一个字母。
s = sb.reverse().toString() + str.charAt(str.length() - 1);
//与最终结果合并
finalString.append(s).append(" ");
}
//打印最终结果
System.out.println(finalString.toString().trim());
}
}
我所做的是,首先将所有单词按空格分割并存储在数组中。然后遍历数组,从每个单词中获取子字符串,去掉每个单词的最后一个字母。然后我使用StringBuilder来反转字符串。完成后,我将单词的最后一个字母添加到反转后的字符串中,并与创建的finalString合并。
英文:
Below is the solution to solve the problem:
public class Main {
public static void main(String[] args) {
//call the reverseSentence Method
reverseSentence("Hello how are you");
}
public static void reverseSentence(String sentence) {
//Replacing multiple space with a single space
sentence = sentence.replaceAll("[ ]{2,}", " ");
//Split the array and store in an array
String [] arr = sentence.split(" ");
StringBuilder finalString = new StringBuilder();
//Iterate through the array using forEach loop
for(String str : arr) {
//Creating substring of the word, leaving the last letter
String s = str.substring(0, str.length() - 1);
//Creating StringBuilder object and reversing the String
StringBuilder sb = new StringBuilder(s);
//Reversing the string and adding the last letter of the work again.
s = sb.reverse().toString() + str.charAt(str.length() - 1);
//Merging it with the final result
finalString.append(s).append(" ");
}
//Printing the final result
System.out.println(finalString.toString().trim());
}
}
What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.
答案2
得分: 1
Sure, here's the translated code part:
我会使用正则表达式的 `replaceAll` 方法结合 lambda 表达式来处理字符串的反转。`\S+` 匹配任意非空格字符序列。这样做的优点是能够优雅地处理任意空白字符。如果你想避免反转标点字符,可以使用 `\w+`,不过匹配像 `"isn't"` 这样的单词则意味着问题涉及到了自然语言处理。不过我假设你的需求没有那么复杂。
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String res = Pattern
.compile("\\S+")
.matcher("Hello how are you")
.replaceAll(m -> {
String s = m.group();
return new StringBuilder(s.substring(0, s.length() - 1))
.reverse().toString() + s.charAt(s.length() - 1);
});
System.out.println(res); // => lleHo ohw rae oyu
}
}
如果你有任何其他问题,欢迎随时问我。
英文:
I'd use regex replaceAll
with a lambda to handle the reversal. \S+
matches any sequence of non-space characters. This has the advantage of elegantly handling arbitrary whitespace. You could use \w+
if you want to avoid reversing punctuation characters, although matching words like "isn't"
and so forth suggests the problem devolves into natural language processing. I assume your specification is not so complex, though.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String res = Pattern
.compile("\\S+")
.matcher("Hello how are you")
.replaceAll(m -> {
String s = m.group();
return new StringBuilder(s.substring(0, s.length() - 1))
.reverse().toString() + s.charAt(s.length() - 1);
});
System.out.println(res); // => lleHo ohw rae oyu
}
}
答案3
得分: 0
一个更简单的解决方案是仅使用Java中的[Stack](https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html)数据结构,针对每个单词(在执行string.split操作后)执行以下操作:将每个字母(除了token.length-1位置的字母)添加到栈中。
public static void main(String[] args) {
String string = "Hello how are you ";
final String[] tokens = string.split(" ");
for (String token : tokens) {
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < token.length()-1; i++) {
stack.push(token.charAt(i));
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.print(token.charAt(token.length()-1) + " ");
}
}
英文:
A simpler solution would be to just use the Java Stack data structure for each word (after a string.split) and just add each letter (except token.length-1).
public static void main(String[] args) {
String string = "Hello how are you ";
final String[] tokens = string.split(" ");
for (String token : tokens) {
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < token.length()-1; i++) {
stack.push(token.charAt(i));
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.print(token.charAt(token.length()-1) + " ");
}
}
答案4
得分: 0
以下是您要求的代码的翻译部分:
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
System.out.print(ch[i]);
for(int j=i-2;j>=pos;j--)
{
System.out.print(ch[j]);
}
System.out.print(ch[i-1]);
pos=i+1;
}
}
}
}
英文:
How do you think of this solution?
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
System.out.print(ch[i]);
for(int j=i-2;j>=pos;j--)
{
System.out.print(ch[j]);
}
System.out.print(ch[i-1]);
pos=i+1;
}
}
}
}
答案5
得分: 0
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
final List<String> list = Arrays.asList(s.split(" "));
StringBuilder builder = new StringBuilder();
list.forEach(item -> {
StringBuilder itemBuilder = new StringBuilder(item);
final String rStr = itemBuilder.reverse().toString();
builder.append(rStr.substring(1, rStr.length())).append(rStr.substring(0, 1)).append(" ");
});
System.out.println(builder.toString());
}
}
英文:
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
final List<String> list = Arrays.asList(s.split(" "));
StringBuilder builder = new StringBuilder();
list.forEach(item ->{
StringBuilder itemBuilder = new StringBuilder(item);
final String rStr = itemBuilder.reverse().toString();
builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
});
System.out.println(builder.toString());
}
}
答案6
得分: 0
FP风格:
String str = "Hello how are you";
String res = Arrays.stream(str.split(" "))
.map(s ->
new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
)
.reduce((s, s1) -> s + " " + s1)
.orElse("");
System.out.println(res); // lleHo ohw rae oyu
英文:
FP style:
String str = "Hello how are you";
String res = Arrays.stream(str.split(" "))
.map(s ->
new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
)
.reduce((s, s1) -> s + " " + s1)
.orElse("");
System.out.println(res); // lleHo ohw rae oyu
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论