簡體   English   中英

檢查字符串中的值的函數

[英]Function that checks for a value inside a string

我正在開發一個通過藍牙與PCB通信的應用程序。 我從應用程序發送到PCB十六進制字符串,如下所示:

hex_string = 2b0509045af2ff1f5230a9072b

嗯,在此字符串中,這些值始終是相同的2b050904 ,而其他兩個值分別代表5af2ff1f存儲位置, 5230a907變量值和2b校驗和。

開頭的2b代表thread init ,所以基本上我需要檢查字符串中的其他2b ,因為如果有另一個2b ,PCB將把它理解為另一個線程init並將整個字符串拆分。

因此,步驟如下:

* Disregarding the 2b at the start, check for another 2b inside the string, and if it is,
  duplicate it, so the PCB understands it this way.
* Afther duplicating the 2b, change the 09 in the non variable part of the string, 
  that indicates the string's byte length, with a 0a.

在該線程中進行討論之后: 檢查字符串中的especific值

這是我用來實現此目的的功能:

public static String manage2b (String s) {
    String sNew = null;
    String input = null;

    if (s.contains("2b")) {
        sNew = s.replaceFirst("2b", "");
    }
    if (sNew.contains("2b")) {
        input = convertString(s);
        input = replaceSize(input, "0a");
    }
    else {
        input = s;
    }
    return input;
}
/**Changes the 09 for 0a as the string's byte length if there is a duplicated "2b"*/
private static String replaceSize (String input, String newSizeVal) {
    int sizePosition = 4;
    return input.substring(0, sizePosition) + newSizeVal + input.substring(sizePosition + newSizeVal.length(), input.length());
}
/**Duplicates the "2b" if there is another inside the string*/
public static String convertString (String input) {
    String find2b = "2B";

    int firstIndex = input.indexOf(find2b) + find2b.length();
    return input.substring(0, firstIndex) + input.substring(firstIndex, input.length()).replace(find2b, "2B2B");
}

我已經用調試器檢查了該函數,並使用了一個與示例中的字符串非常相似的字符串,它使從090a的更改正確0a ,但它沒有復制2b 因此,我認為在執行此步驟時,也許我聲明了錯誤,或者在某個地方犯了錯誤。

是的...“ 2b”與“ 2B”不同...對其進行更改...我認為之后它會起作用...(我不允許發表評論..對不起..)

如果String不尋找大小寫匹配,這似乎是正確的。

另外,您是否只需要檢查一個重復出現的“ 2b”,還是可能要檢查幾個? while(s.contains(“ 2b”)|| s.contains(“ 2B”))

可以幫助您。

至於區分大小寫:

org.apache.commons.lang3.StringUtils.containsIgnoreCase(“ ABCDEFGHIJKLMNOP”,“ gHi”);

可以為您提供幫助,因此:

導入org.apache.commons.lang3.StringUtils; ...

while(StringUtils.containsIgnoreCase(s,“ 2b”))...

應該解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM