gpt4 book ai didi

java - 为什么方法中输入的最后一个字符串首先被打印?

转载 作者:行者123 更新时间:2023-12-01 19:06:39 26 4
gpt4 key购买 nike

import java.util.*;
public class Hello {
public static void undoOper(String str) {
List<Character> lis = new ArrayList<>();
char[] arr = str.toCharArray();
for (char ch : arr) {
lis.add(ch);
}
for (int i = 0; i < lis.size(); i++) {
if (lis.get(i) == '^') {
lis.remove(i);
lis.remove(i - 1);
i = i - 2;
}
}
if (lis.size() == 0)
System.out.print("-1");
for (int i = 0; i < lis.size(); i++) {
System.out.print(lis.get(i));
}

System.out.println();
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String[] str = new String[N];
for (int i = 0; i < N; i++) {
str[i] = sc.nextLine();
}
for (int i = 0; i < N; i++) {
undoOper(str[i]);
}
}
}

该程序用于撤消操作该程序接受 N 个字符串值。字符 ^ 表示撤消操作以清除最后一个前一个字符。

输入:

Hey ^goooo^^glee^
ora^^nge^^^^

输出:

Hey google
-1(since all char gets erased)

我的输出:

-1
Hey google

最佳答案

final static Pattern pattern = Pattern.compile("\\^", Pattern.MULTILINE);

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); //because \n is appended with previous nextInt
sc.nextLine();
String[] outPut = new String[N];
for (int i = 0; i < outPut.length; i++) {
String input = sc.nextLine();
Matcher matcher = pattern.matcher(input);
input = matcher.replaceAll("");
outPut[i] = input;
}
sc.close();
System.out.println(Arrays.asList(outPut));
}

看看这是否对您有帮助

关于java - 为什么方法中输入的最后一个字符串首先被打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59541648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com