简体   繁体   中英

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. 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.

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:

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. 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. 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)

This will remove the 7th ^A and everything following it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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