[英]Java - remove new-lines from byte array
所以我目前正在嘗試使用這種(極其低效的)方法從字節數組中刪除換行符
public void fixPasswords() {
ArrayList<Byte> active = new ArrayList<>();
ArrayList<Byte> stored = new ArrayList<>();
for (byte b : activePassword) {
if (b!='\n'||b!='\r') {
active.add(b);
}
}
activePassword = new byte[active.size()];
for (int i = 0; i < active.size(); i++) {
activePassword[i] = active.get(i);
}
for (byte b : storedPassword) {
if (b!='\n'||b!='\r') {
stored.add(b);
}
}
storedPassword = new byte[stored.size()];
for (int i = 0; i < stored.size(); i++) {
storedPassword[i] = stored.get(i);
}
activePasswordString = new String(activePassword);
storedPasswordString = new String(storedPassword);
System.out.println("Active: "+activePasswordString);
System.out.println("Stored: "+storedPasswordString);
}
但是,它不會刪除換行符
Active: fK��f3�Nc1L�2*j�JQ��b�@|�`
Stored: >K�U�0p
uvn��B�
存儲的密碼似乎仍然保留換行符,我將如何檢測字節數組中的換行符並將其刪除?
您應該使用&&(和)運算符,而不是|| (或)運算符。
您的代碼:
if (b!='\n'||b!='\r')
嘗試以下方法:
if (b!='\n'&&b!='\r')
or運算符僅需要條件之一就可以將其評估為true
以使其為true
。 即使b
等於'\\n'
, b!='\\r'
,反之亦然。 因此, or表達式將始終為true,並且您將添加字節數組中的每個字符。
嗯,類似的東西怎么樣:
public void fixPasswords() {
byte[] activePassword = "fK��\u000Ef3�Nc1\fL�2*j�JQ��b�@|�`\r".getBytes();
byte[] storedPassword = ">K�U�0p\nuvn��B�".getBytes();
String activePasswordString = parsePassword(activePassword);
String storedPasswordString = parsePassword(storedPassword);
System.out.println("Active: "+activePasswordString);
System.out.println("Stored: "+storedPasswordString);
}
private String parsePassword(byte[] password){
return new String(password).replaceAll("[\\n\\r]", "");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.