简体   繁体   English

Java 基于第 n 个分隔符的字符串修剪 position

[英]Java String trim based on delimiter nth position

I have a java method in which trying to parse a string where fields are delimited by char ^A.我有一个 java 方法,在该方法中尝试解析字段由 char ^A 分隔的字符串。 Sample string like below.示例字符串如下所示。

HDR^A1^A20220106^ATYPE^AXXX^AJAPAN^AUNIFORM^AHELP^AEXAMPLE^A

I have attempted to use apache ordinalIndexOf but so far not yet successful with the same.我曾尝试使用 apache ordinalIndexOf 但到目前为止还没有成功。

Could you please help to suggest if any other alternative approach available for this scenario.您能否帮助建议是否有任何其他替代方法可用于这种情况。

public class HelloWorld{

public static int ordinalIndexOf(String str, String substr, int n) {

    int pos = str.indexOf(substr);

    while (--n > 0 && pos != -1)

        pos = str.indexOf(substr, pos+1);

    return pos;

}
     public static void main(String []args){
//Just kept it here as I need to use standards.. not using in below code
         String CTRL_A = Character.valueOf((char) 0x01).toString();    
     String str = "HDR^ABYE^A20220103065014^Agoogle.com_29958^ABUDDY^A1.0^A123456789012^AHAI^ABYE";

              int position = ordinalIndexOf(str,"^A",6);

        System.out.println(str.substring(0,position));

     }

}

Expected Output String:预期 Output 字符串:

EVENT_HDR^ABYE^A20220103065014^Agoogle.com_29958^ABUDDY^A1.0^A123456789012 EVENT_HDR^ABYE^A20220103065014^Agoogle.com_29958^ABUDDY^A1.0^A123456789012

Referred Link 参考链接

If someone has to downvote question, feel free to leave comment on reason why you do so, it will help to improve self to ask better questions.如果有人不得不对问题投反对票,请随时对您这样做的原因发表评论,这将有助于提高自我提出更好的问题。 I do some self research always before request for help, so please help to do so.在请求帮助之前,我总是做一些自我研究,所以请帮助这样做。

You could try to use the.indexOf() method.您可以尝试使用 .indexOf() 方法。 So, in this case try:因此,在这种情况下尝试:

String str = "HDR^A1^A20220106^ATYPE^AXXX^AJAPAN^AUNIFORM^AHELP^AEXAMPLE^A";
System.out.println(str.indexOf("^A"));

This will print the index of the first appearance of the given substring.这将打印给定 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的第一次出现的索引。 Alternatively, you could do:或者,您可以这样做:

String str = "HDR^A1^A20220106^ATYPE^AXXX^AJAPAN^AUNIFORM^AHELP^AEXAMPLE^A";
System.out.println(str.indexOf("^A", 10)); // Start at index 10.

Please refer to the documention here for more: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)有关更多信息,请参阅此处的文档: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)

This will remove the 7th ^A and everything following it:这将删除第 7 个^A及其后面的所有内容:

str = str.replaceAll("((.*?^A){6})^A.*", "$1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM