gpt4 book ai didi

java - 注释结束或结束语句后拆分字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:13 26 4
gpt4 key购买 nike

我有一个代码:

String code = "class foo { // class named foo\n
public void fo() { // a method no parameter named fo\n
int[]a = {\n
1,2,3,4\n
};\n
for(int b : a){ // loop b as many as a\n
if(b%2==0){\n
System.out.println(b); // print out b\n
}\n
}\n
}\n
}";

因此,我想在每个注释结束或语句结束后将代码拆分为单独的字符串。这是一个例子:

1. class foo { // class named foo
2. public void fo() { // a method no parameter named fo
3. int[]a = {
1,2,3,4
};
4. for(int b : a){ // loop b as many as a
5. if(b%2==0){
System.out.println(b); // print out b

我正在尝试编写代码:

for(String get : code.split("(?<=;)|(?<=;(//.+))"))

但是,它不起作用。

最佳答案

这会准确地打印出您想要实现的目标...

public static void main(String[] args) {
try {
String code = "class foo { // class named foo\n" +
"public void fo() { // a method no parameter named fo\n" +
"int[]a = {\n" +
" 1,2,3,4\n" + "};\n" +
"for(int b : a){ // loop b as many as a\n" +
"if(b%2==0){\n" +
" System.out.println(b); // print out b\n" +
"}\n" + "}\n" + "}\n" + "}";

String requiredData = "";
short count = 1;
for (String data : code.split("\n")) {
if (data.contains("//") || data.contains(";")) {
requiredData = requiredData + data;
System.out.println(count + ". " + requiredData);
requiredData = "";
count++;
} else {
if (requiredData.isEmpty())
requiredData = data + "\n";
else
requiredData = requiredData + data + "\n";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

这是上面代码的输出...

1. class foo { // class named foo
2. public void fo() { // a method no parameter named fo
3. int[]a = {
1,2,3,4
};
4. for(int b : a){ // loop b as many as a
5. if(b%2==0){
System.out.println(b); // print out b

关于java - 注释结束或结束语句后拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959007/

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