java—在chararray中的某个字符之后向字符串添加8个字符

x759pob2  于 2021-07-06  发布在  Java
关注(0)|答案(4)|浏览(417)

我有这个字符串:

}1311202013112020607169018}1611202016112020}1411202014112020626948615}1511202015112020}1811202018112020

为了让你明白,我会这样把它分开:

}13112020 13112020607169018 }16112020 16112020 }14112020 14112020626948615 }15112020 15112020 
}18112020 181120207834

我要做的是在表示日期的'}'字符后面加上前八个字符(数字)。其他我根本不需要的号码。
我用for循环尝试了很多不同的方法,这是最后一段代码。

for (int i = 0; i < Char.length; i++) {

     if(Char[i] == '}') {

          newString = newString + Char[i + 6];

     } 
}

所以我试着用这样的线来结束

}13112020}16112020}14112020}15112020}18112020

另外,如果有人能给我一个提示,告诉我如何创建(如果可能的话)x个新字符串,每个字符串都是一个不同的名称,只包含其中一个日期。
谢谢您!

rur96b6h

rur96b6h1#

据我所知,你需要这样的东西

static List<String> getDates(String str){
      String[] arr = str.split("}");
      ArrayList<String> out = new ArrayList<>();
      for (int i = 0;i < arr.length;i++){
            arr[i] = arr[i].trim(); //remove any spaces
            if (arr[i].length() == 0) continue;
            out.add(arr[i].subString(0 , Math.min(arr[i].length() , 6)); //to prevent any OutOfBounds Errors

      }
      return out;
}
fzsnzjdm

fzsnzjdm2#

我们可以在这里尝试使用正则表达式字符串拆分:

String input = "}1311202013112020607169018}1611202016112020}1411202014112020626948615}1511202015112020}1811202018112020";
String[] parts = input.split("(?<=\\}\\d{8})|(?=\\})");
System.out.println(Arrays.toString(parts));

这张照片:

[}13112020, 13112020607169018, }16112020, 16112020, }14112020, 14112020626948615,
 }15112020, 15112020, }18112020, 18112020]

正则表达式表示在字符串中的任意点拆分,其中:

(?<=\\}\\d{8})   what precedes is } followed by 8 digits
|                OR
(?=\\})          what follows is }

编辑:
如果您接受了答案,那么您似乎真的需要以下输出:

}13112020}16112020}14112020}15112020}18112020

为此,我建议使用一个简单的regex替换:

String input = "}1311202013112020607169018}1611202016112020}1411202014112020626948615}1511202015112020}1811202018112020";
String output = input.replaceAll("(\\}\\d{8})\\d*", "$1");
System.out.println(output);

这张照片:

}13112020}16112020}14112020}15112020}18112020
dm7nw8vv

dm7nw8vv3#

您可以利用regex查找与您的模式匹配的所有子字符串。这个例子中的正则表达式是 "\}[0-9]{8}" (您在右大括号后面说6个字符,但您的示例显示了8个字符)。
在java中,您可以使用 Pattern 以及 Matcher 要编译此正则表达式并查找所有匹配的子字符串:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

String str = "}1311202013112020607169018}1611202016112020}1411202014112020626948615}1511202015112020}1811202018112020";

Pattern pattern = Pattern.compile("\\}[0-9]{8}");  // have to double-escape brace
Matcher matcher = pattern.matcher(str);

// we use StringBuilder to concatenate the results
StringBuilder result = new StringBuilder();
while(matcher.find()) {
  result.append(matcher.group());
}

System.out.println(result.toString());
py49o6xq

py49o6xq4#

一个简单的方法:

String text = new String(Char);
List<String> lists = new ArrayList<String>();
String[] split = text.split("}");

for(String first: split) {
    lists.add(first.substring(0,5));
}

相关问题