In my android project, i want to read a data structure from file. A field suppose 'name', which has maximum of 32 chars. Most of the time 'name' field contains less than maximum limit. Some unwanted chars (i think 'null') is filled with data. i used 'trim' method to remove, but nothing happened. I need only valid data for processing, how can i solve this problem ?
使用正则表达式替换不可打印的字符。
String string=line.replaceAll("[^\\p{Print}]","");
Check whether the ascii value of the character is greater than 0 to check whether the character is null
How to remove null from android String
String str = "abc def";
StringBuffer sb = new StringBuffer();
byte[] byteArray = str.getBytes();
for(byte bytedata:byteArray){
if(bytedata>0){
sb.append((char)bytedata);
}
}
str = sb.toString();
System.out.println("..."+str);
If the char 0 is appended at the end of the String, just find its first index in the String, and substring up to this index:
int nullCharIndex = s.indexOf((char) 0);
if (nullCharIndex >= 0) {
s = s.substring(0, nullCharIndex);
}
If you have a name field that is completly null just check, whether the string == null.
If you want to parse one string, which contains for example spaces jsut use:
String string = "a b c d";
string.replaceAll(" ","");
This can be used for every other char. Be aware that you have to use RegEx for that.
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.