java6.将“to be or not to be ” 变为 “ot eb ro ton ot eb”
时间: 2023-10-07 13:08:28 浏览: 127
以下是Java代码实现:
```java
public class ReverseWords {
public static void main(String[] args) {
String sentence = "to be or not to be";
String[] words = sentence.split(" ");
StringBuilder reversed = new StringBuilder();
for (String word : words) {
StringBuilder wordBuilder = new StringBuilder(word);
reversed.append(wordBuilder.reverse()).append(" ");
}
System.out.println(reversed.toString().trim());
}
}
```
运行结果为:
```
ot eb ro ton ot eb
```
相关问题
java 测试输入: oT eb ro ton ot eb 预期输出:To be or not to be
在Java中,测试输入通常涉及到单元测试,这里你提到的是字符串处理的一个场景。如果你想要编写一个函数来检查输入是否符合特定模式,例如判断字符串"oT eb ro to"是否按照预期转换成"To be or not to be",你可以创建一个简单的测试用例。下面是一个示例:
```java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringManipulationTest {
private String toBeOrNottoBe(String input) {
// 这里假设有一个将 "oT eb ro to" 转换的逻辑
return input.replace("eb", "be").replace("ot ", "to ");
}
@Test
public void testInput() {
String input = "oT eb ro to";
String expectedOutput = "To be or not to be";
String actualOutput = toBeOrNottoBe(input);
assertEquals(expectedOutput, actualOutput); // 测试期望的结果是否等于实际结果
}
}
```
在这个例子中,`toBeOrNottoBe`方法接收输入并应用相应的替换规则。然后,在`testInput`测试方法中,我们传入"oT eb ro to"作为输入,期望输出与预期一致。
java编写程序:使得该程序可以将一段英文句子中的每个单词里的字母顺序颠倒,例如 “to be or not to be ” 变为 “ot eb ro ton ot eb”
以下是Java程序实现:
```java
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一段英文句子:");
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
StringBuilder reverse = new StringBuilder(word);
reverse.reverse();
result.append(reverse).append(" ");
}
System.out.println("颠倒顺序后的句子为:" + result.toString().trim());
}
}
```
运行程序后,输入一段英文句子,程序将输出颠倒每个单词字母顺序后的句子。例如,输入 "to be or not to be",程序将输出 "ot eb ro ton ot eb"。
阅读全文