java - Fastest way to check if comma separated string contains at least 1 valid integer? -
i have string comma separated positive integers, example:
1,34,433,12 what fastest way determine if string contains @ least 1 integer?
right split(","), loop on resulting string[] , try parse each element int.
this works in order list<integer> of string want fastest way possible determine if string valid this.
1a,2b,13 acceptable. 1a,2b,13c not acceptable.
try:
public static boolean containsint(string string) { boolean onlydigits = true; boolean atleastonedigit = false; int len = string.length(); (int = 0; < len; i++) { char c = string.charat(i); if (c == ',') { if (atleastonedigit && onlydigits) { return true; } onlydigits = true; atleastonedigit = false; continue; } boolean isdigit = c >= '0' && c <= '9'; onlydigits &= isdigit; atleastonedigit |= isdigit; } return atleastonedigit && onlydigits; } now, more readable version using guava:
public static boolean containsint(string text) { (string s : splitter.on(',').split(text) { if (ints.tryparse(s) != null) return true; } return false; }
Comments
Post a Comment