Java 如何按索引位置旋转单词?
我正在读一个输入文件,其中新行包含两个句子。我必须编写一个代码,将句子中的每个单词向右旋转,然后写入output.txt文件。例如,input.txt文件包含以下内容:Java 如何按索引位置旋转单词?,java,Java,我正在读一个输入文件,其中新行包含两个句子。我必须编写一个代码,将句子中的每个单词向右旋转,然后写入output.txt文件。例如,input.txt文件包含以下内容: Hello World. Welcome to java programming. 假设“Hello”有索引1。它应该向右旋转1个位置,即oHell。“世界”有指数2,它应该向右旋转2个位置,即ldWor.,保持周期(.) 在下一行,索引再次以1开始。i、 e.索引1的“欢迎”应向右旋转1个位置,“至”索引2的“至”应向右旋转
Hello World.
Welcome to java programming.
假设“Hello”有索引1。它应该向右旋转1个位置,即oHell。“世界”有指数2,它应该向右旋转2个位置,即ldWor.,保持周期(.)
在下一行,索引再次以1开始。i、 e.索引1的“欢迎”应向右旋转1个位置,“至”索引2的“至”应向右旋转2个位置,“java”索引3的“java”应向右旋转3个位置,“编程”索引4的“编程”应向右旋转4个位置
因此,输出应为:
oHell ldWor.
eWelcom to avaj mingprogram.
下面是我的代码:
public static void main(String[] args) throws IOException {
rotate();
}
private static void rotate() throws IOException {
FileInputStream inputFile = new FileInputStream("input.txt");
FileWriter outputFile = new FileWriter("output.txt");
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String last = "";
if(line.charAt(line.length()-1) == '.'){
last = ".";
line = line.substring(0,line.length()-1);
}
String str[] = line.split(" ");
outputFile.write(IntStream.range(0, str.length-1).mapToObj(i -> rotate(str[i], i)).collect(Collectors.joining(" ")) +last+ "\n");
}
inputFile.close();
outputFile.close();
scanner.close();
}
private static String rotate(String str, int position) {
return str.substring(str.length()-position)+str.substring(0,str.length()-position);
}
Hello.
Welcome ot vaja.
oHell ldWor.
eWelcom to avaj mingprogram.
oHell ldWor.
eWelcom to avaj mingprogram PO.
输出获取:
public static void main(String[] args) throws IOException {
rotate();
}
private static void rotate() throws IOException {
FileInputStream inputFile = new FileInputStream("input.txt");
FileWriter outputFile = new FileWriter("output.txt");
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String last = "";
if(line.charAt(line.length()-1) == '.'){
last = ".";
line = line.substring(0,line.length()-1);
}
String str[] = line.split(" ");
outputFile.write(IntStream.range(0, str.length-1).mapToObj(i -> rotate(str[i], i)).collect(Collectors.joining(" ")) +last+ "\n");
}
inputFile.close();
outputFile.close();
scanner.close();
}
private static String rotate(String str, int position) {
return str.substring(str.length()-position)+str.substring(0,str.length()-position);
}
Hello.
Welcome ot vaja.
oHell ldWor.
eWelcom to avaj mingprogram.
oHell ldWor.
eWelcom to avaj mingprogram PO.
预期输出:
public static void main(String[] args) throws IOException {
rotate();
}
private static void rotate() throws IOException {
FileInputStream inputFile = new FileInputStream("input.txt");
FileWriter outputFile = new FileWriter("output.txt");
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String last = "";
if(line.charAt(line.length()-1) == '.'){
last = ".";
line = line.substring(0,line.length()-1);
}
String str[] = line.split(" ");
outputFile.write(IntStream.range(0, str.length-1).mapToObj(i -> rotate(str[i], i)).collect(Collectors.joining(" ")) +last+ "\n");
}
inputFile.close();
outputFile.close();
scanner.close();
}
private static String rotate(String str, int position) {
return str.substring(str.length()-position)+str.substring(0,str.length()-position);
}
Hello.
Welcome ot vaja.
oHell ldWor.
eWelcom to avaj mingprogram.
oHell ldWor.
eWelcom to avaj mingprogram PO.
有人能帮忙吗?谢谢。有两个小问题导致代码无法按预期方式运行。首先,您跳过了行中的最后一个单词,因为
IntStream(0,4)
经过0,1,2,3
,而不是4
,因此您不需要执行IntStream.range(0,str.length-1)
第二个问题是,您正在对单词进行0索引(因为这是数组的索引),但您希望对旋转进行1索引。为此,只需执行mapToObj(i->rotate(str[i],i+1)
总的来说,您的大输出行应该是
outputFile.write(
IntStream.range(0, str.length - 1)
.mapToObj(i -> rotate(str[i], i))
.collect(Collectors.joining(" "))
+ last + "\n");
在rotate函数中还有一种情况,即旋转量可能大于单词的长度,在这种情况下,请尝试从负位置进行子串。若要解决此问题,请通过执行以下操作确保旋转量在范围内[0,str.length())
:
position = ((position % str.length()) + str.length()) % str.length();
按以下方式旋转字符串中的单词:
public class Main {
public static void main(String[] args) {
String[] arr = { "Hello World.", "Welcome to java programming OP." };
// Test
for (String s : arr) {
System.out.println(rotate(s));
}
}
static String rotate(String str) {
// Split the string on space(s)
String[] words = str.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
// If `words[i]` contains a punctuation mark at the end, drop it.
char lastChar = words[i].charAt(words[i].length() - 1);
boolean noPunct = false;
if (Character.isDigit(lastChar) || Character.isLetter(lastChar)) {
noPunct = true;
}
String word = !noPunct ? words[i].substring(0, words[i].length() - 1) : words[i];
// Rotate the word
String rotatedWord = "";
if (i > word.length()) {
for (int j = 0; j <= i; j++) {
rotatedWord = word.substring(word.length() - j % word.length() - 1)
+ word.substring(0, word.length() - j % word.length() - 1);
}
} else {
rotatedWord = word.substring(word.length() - i - 1) + word.substring(0, word.length() - i - 1);
}
// Append the rotated word to `sb`
sb.append(rotatedWord);
// If `words[i]` had a punctuation mark at the end, add it back
if (!noPunct) {
sb.append(lastChar);
}
if (lastChar != '.') {
sb.append(" ");
}
}
return sb.toString();
}
}
我会使用
模式
和匹配器
来识别单词。在旋转每个单词时,您需要小心处理右移位大于单词长度的情况:
static String reverse(String line)
{
StringBuilder b = new StringBuilder();
Pattern p = Pattern.compile("([a-zA-Z]+)([\\s.,]+)");
Matcher m = p.matcher(line);
for(int i=1; m.find(); i++)
{
String word = m.group(1);
int idx = word.length() - (i % word.length());
b.append(word.substring(idx));
b.append(word.substring(0, idx));
b.append(m.group(2));
}
return b.toString();
}
测试:
输出:
oHell ldWor.
eWelcom to avaj mingprogram, ti is yreall unf.
但当我这样做时,outputFile.write(IntStream.range(0,str.length).mapToObj(I->rotate(str[I],I+1)).collect(Collectors.joining(“”)+last+“\n”);=>这会引发以下异常:线程“main”中的异常Java.Lang.String索引xOutOfFunsExtry:String index超出范围:-2对上面的语句有任何想法?你的旋转函数存在一个问题。你没有考虑这个单词比你要旋转的量短的情况。考虑调用<代码>旋转(“HI”,5);这里会发生什么?应该是“IH”。第五次轮换后是的。请参阅本文的编辑部分,了解如何修复您的轮换功能。如果长句末尾有短词,则此代码将无效。有关详细信息和解决方案,请参阅本文的正确答案。当我使用较长的句子时,它会抛出StringIndexOutOfBoundException。应该怎么做?@ArvindKumarAvinash,现在是第二个字符串超出了绑定范围,如果我向其中添加更多单词,则会出现异常it@AkshayShinde-在您发表评论后,我已解决了此问题,但忘记了让您知道。我希望更新的答案满足您的要求。您只考虑将
作为代码中的标点符号。但是,标点符号可以是中的一个“#$%&”()*+,-./:;?@[\]^
{124;}`。有关详细信息,请查看。