• String工具类


    1、第一个 

    1. package com.tigeriot.mqtt.util;
    2. import java.util.ArrayList;
    3. import java.util.List;
    4. import java.util.StringTokenizer;
    5. import com.alibaba.fastjson.JSON;
    6. import org.springframework.util.StringUtils;
    7. public class StringUtil {
    8. //
    9. /**
    10. * 将字符串的首字母转大写
    11. *
    12. * @param str
    13. * 需要转换的字符串
    14. * @return
    15. */
    16. public static String captureName(String str) {
    17. // 进行字母的ascii编码前移,效率要高于截取字符串进行转换的操作
    18. char[] cs = str.toCharArray();
    19. cs[0] -= 32;
    20. return String.valueOf(cs);
    21. }
    22. /**
    23. *
    24. * @param str_source
    25. * @param str_target
    26. * @return
    27. */
    28. public static boolean isEquString(String str_source, String str_target) {
    29. boolean flag = false;
    30. try {
    31. if (str_target.equals(str_source)) {
    32. flag = true;
    33. }
    34. } catch (Exception e) {
    35. // TODO: handle exception
    36. }
    37. return flag;
    38. }
    39. ///
    40. public static String getNameDepart(String realname) {
    41. try {
    42. // String mobile = "15888888888";
    43. String realname1 = null;
    44. char[] r = realname.toCharArray();
    45. // char[] m = mobile.toCharArray();
    46. if (r.length == 1) {
    47. realname1 = realname;
    48. }
    49. if (r.length == 2) {
    50. realname1 = realname.replaceFirst(realname.substring(1), "*");
    51. }
    52. if (r.length > 2) {
    53. realname1 = realname.replaceFirst(realname.substring(1, r.length - 1), "*");
    54. }
    55. // for (int i = 0; i < m.length; i++) {
    56. // if (i > 2 && i < 7) {
    57. // m[i] = '*';
    58. // }
    59. // }
    60. // String mobile1 = String.valueOf(m);
    61. // System.out.println(realname1);// 程*员
    62. // System.out.println(mobile1);// 158****8888
    63. return realname1;
    64. } catch (Exception e) {
    65. // TODO: handle exception
    66. return realname;
    67. }
    68. }
    69. ///
    70. public static String decodeby10(String str) {
    71. StringBuffer out = new StringBuffer();
    72. if (str == null || ("".equals(str)))
    73. return "";
    74. char[] chars = str.toCharArray();
    75. for (int i = 0; i < chars.length; i++) {
    76. if ((chars[i] >= 19968 && chars[i] <= 40869) // 中日朝兼容形式的unicode编码范围:
    77. // U+4E00——U+9FA5
    78. || (chars[i] >= 11904 && chars[i] <= 42191)// 中日朝兼容形式扩展
    79. || (chars[i] >= 63744 && chars[i] <= 64255)// 中日朝兼容形式扩展
    80. || (chars[i] >= 65072 && chars[i] <= 65103)// 中日朝兼容形式扩展
    81. || (chars[i] >= 65280 && chars[i] <= 65519)// 全角ASCII、全角中英文标点、半宽片假名、半宽平假名、半宽韩文字母的unicode编码范围:U+FF00——U+FFEF
    82. || (chars[i] >= 32 && chars[i] <= 126)// 半角字符的unicode编码范围:U+0020-U+007e
    83. || (chars[i] >= 12289 && chars[i] <= 12319)// 全角字符的unicode编码范围:U+3000——U+301F
    84. ) {
    85. out.append(chars[i]);
    86. }
    87. }
    88. String result = out.toString().trim();
    89. result = result.replaceAll("\\?", "").replaceAll("\\*", "").replaceAll("<|>", "").replaceAll("\\|", "")
    90. .replaceAll("/", "");
    91. return result;
    92. }
    93. /**
    94. *
    95. * 判断为 16进制字符串
    96. *
    97. * @param str
    98. * @return
    99. */
    100. public static boolean isHexStr(String str) {
    101. boolean isHexFlg = true;
    102. int i = 0;
    103. char c;
    104. for (i = 0; i < str.length(); i++) {
    105. c = str.charAt(i);
    106. if (!(((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'F')) || (c >= 'a') && (c <= 'f'))) {
    107. isHexFlg = false;
    108. }
    109. }
    110. return isHexFlg;
    111. }
    112. /*
    113. * Convert byte[] to hex
    114. * string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
    115. *
    116. * @param src byte[] data
    117. *
    118. * @return hex string
    119. */
    120. public static String bytesToHexString(byte[] src) {
    121. StringBuilder stringBuilder = new StringBuilder("");
    122. if (src == null || src.length <= 0) {
    123. return null;
    124. }
    125. for (int i = 0; i < src.length; i++) {
    126. int v = src[i] & 0xFF;
    127. String hv = Integer.toHexString(v);
    128. if (hv.length() < 2) {
    129. stringBuilder.append(0);
    130. }
    131. stringBuilder.append(hv);
    132. }
    133. return stringBuilder.toString();
    134. }
    135. /**
    136. * Convert hex string to byte[]
    137. *
    138. * @param hexString
    139. * the hex string
    140. * @return byte[]
    141. *
    142. * 2019年11月23日14:49:05
    143. *
    144. * 16进制 字符串 转 16进制数组
    145. */
    146. public static byte[] HexStringToHexBytes(String hexString) {
    147. try {
    148. if (hexString == null || hexString.equals("")) {
    149. return null;
    150. }
    151. if (!isHexStr(hexString)) {
    152. throw new Exception( "不合法的十六进制!");
    153. }
    154. hexString = hexString.toUpperCase();
    155. int length = hexString.length() / 2;
    156. char[] hexChars = hexString.toCharArray();
    157. byte[] d = new byte[length];
    158. for (int i = 0; i < length; i++) {
    159. int pos = i * 2;
    160. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
    161. }
    162. return d;
    163. } catch (Exception e) {
    164. // TODO: handle exception
    165. // return null;
    166. // e.printStackTrace();
    167. System.out.println(e.getMessage());
    168. }
    169. return null;
    170. }
    171. /**
    172. * Convert char to byte
    173. *
    174. * @param c
    175. * char
    176. * @return byte
    177. */
    178. private static byte charToByte(char c) {
    179. return (byte) "0123456789ABCDEF".indexOf(c);
    180. }
    181. /**
    182. *
    183. * 手机号码的加 *
    184. */
    185. // public static String createProxyTokenByParentId(String parentId) {
    186. //
    187. // String token = parentId + "00000000000000000000";
    188. //
    189. // return token;
    190. // }
    191. /**
    192. *
    193. * 手机号码的加 *
    194. */
    195. public static String getTel_PartContent(String tel) {
    196. try {
    197. // 括号表示组,被替换的部分$n表示第n组的内容
    198. tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    199. return tel;
    200. } catch (Exception e) {
    201. // TODO: handle exception
    202. return "***err***";
    203. }
    204. }
    205. /**
    206. * 将字符串以指定字符串切割后,分配到List中
    207. *
    208. * @param strValue-->输入字符串
    209. * @return List
    210. */
    211. public static List getTokenizerList(String strValue, String delim) {
    212. List myList = new ArrayList();
    213. if (strValue == null) {
    214. return myList;
    215. }
    216. StringTokenizer stChat = new StringTokenizer(strValue, delim);
    217. int iLength = stChat.countTokens();
    218. for (int i = 0; i < iLength; i++) {
    219. String strTemp = stChat.nextToken();
    220. if (strTemp == null)
    221. strTemp = "";
    222. myList.add(strTemp);
    223. }
    224. return myList;
    225. }
    226. /**
    227. *
    228. * 将字节数组转为 HEX字符
    229. *
    230. * @param b
    231. */
    232. public static void printHexString(byte[] b) {
    233. for (int i = 0; i < b.length; i++) {
    234. String hex = Integer.toHexString(b[i] & 0xFF);
    235. if (hex.length() == 1) {
    236. hex = '0' + hex;
    237. }
    238. System.out.print(hex.toUpperCase() + "");// + " "
    239. }
    240. System.out.println("");
    241. }
    242. /**
    243. *
    244. * 将字节转为 HEX字符
    245. *
    246. * @param b
    247. */
    248. public static String getHexString(byte b) {
    249. StringBuffer hex_str = new StringBuffer();
    250. try {
    251. String hex = Integer.toHexString(b & 0xFF);
    252. if (hex.length() == 1) {
    253. hex = '0' + hex;
    254. }
    255. hex_str.append(hex.toLowerCase());// + " "//转为小写
    256. return hex_str.toString();
    257. } catch (Exception e) {
    258. return null;
    259. }
    260. }
    261. /**
    262. *
    263. * 将字节数组转为 HEX字符
    264. *
    265. * @param b
    266. */
    267. public static String getHexString(byte[] b) {
    268. StringBuffer hex_str = new StringBuffer();
    269. try {
    270. for (int i = 0; i < b.length; i++) {
    271. String hex = Integer.toHexString(b[i] & 0xFF);
    272. if (hex.length() == 1) {
    273. hex = '0' + hex;
    274. }
    275. hex_str.append(hex.toLowerCase());// + " "//转为小写
    276. }
    277. return hex_str.toString();
    278. } catch (Exception e) {
    279. // TODO: handle exception
    280. return null;
    281. }
    282. }
    283. /**
    284. *
    285. * 将字节数组转为 HEX字符
    286. *
    287. * @param hexString
    288. */
    289. public static String[] getHexStringArr(String hexString) throws Exception {
    290. try {
    291. if (hexString == null || hexString.equals("")) {
    292. return null;
    293. }
    294. if (!isHexStr(hexString)) {
    295. throw new Exception("不合法的十六进制!");
    296. }
    297. String[] strList = new String[hexString.length()/2];
    298. String [] temp = hexString.split("");
    299. int index = 0;
    300. for (int i = 0; i < temp.length; i+=2) {
    301. strList[index] = temp[i] + temp[i+1];
    302. index++;
    303. }
    304. return strList;
    305. } catch (Exception e) {
    306. // TODO: handle exception
    307. // return null;
    308. throw new Exception( "不合法的16进制!");
    309. }
    310. }
    311. /**
    312. *
    313. * 截取字符串后几位
    314. */
    315. public static String subStr(String str, int n) {
    316. if (n < str.length()) {
    317. return str.substring(str.length() - n, str.length());
    318. } else {
    319. return str;
    320. }
    321. }
    322. /***
    323. *
    324. * 去除空格
    325. */
    326. public static String StringTim(String str) {
    327. try {
    328. return str.replaceAll("\\s*", "").trim();
    329. } catch (Exception e) {
    330. e.printStackTrace();
    331. return "";
    332. }
    333. }
    334. /**
    335. *
    336. * 抽取字符串里面的数字
    337. *
    338. * @param str
    339. * @return
    340. */
    341. public static String getNumStr(String str) {
    342. str = str.trim();
    343. String str2 = "";
    344. if (str != null && !"".equals(str)) {
    345. for (int i = 0; i < str.length(); i++) {
    346. if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
    347. str2 += str.charAt(i);
    348. }
    349. }
    350. }
    351. return str2;
    352. }
    353. /**
    354. *
    355. * 判断字符串是否是全数字
    356. *
    357. * @param str
    358. * @return
    359. */
    360. public static boolean isNumStr(String str) {
    361. str = str.trim();
    362. boolean isNum = true;
    363. if (str != null && !"".equals(str)) {
    364. for (int i = 0; i < str.length(); i++) {
    365. if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
    366. } else {
    367. isNum = false;
    368. }
    369. }
    370. } else {
    371. isNum = false;
    372. }
    373. return isNum;
    374. }
    375. /**
    376. * 字符串转化成为16进制字符串
    377. *
    378. * @param s
    379. * @return
    380. */
    381. public static String strTo16(String s) {
    382. String str = "";
    383. for (int i = 0; i < s.length(); i++) {
    384. int ch = (int) s.charAt(i);
    385. String s4 = Integer.toHexString(ch);
    386. str = str + s4;
    387. }
    388. return str;
    389. }
    390. /**
    391. *
    392. * long 转 4个 HEX
    393. *
    394. * @param i
    395. * @return
    396. */
    397. public static String getHex_4formLong(long i) {
    398. String hex4 = "00000000" + Long.toHexString(i);
    399. int length = hex4.length();
    400. return hex4.substring(length - 8, length);
    401. }
    402. /**
    403. *
    404. * long 转 4个 HEX
    405. *
    406. * @param i
    407. * @return
    408. */
    409. public static String getHex_4formInt(int i) {
    410. String hex4 = "00000000" + Integer.toHexString(i);
    411. int length = hex4.length();
    412. return hex4.substring(length - 8, length);
    413. }
    414. /**
    415. *
    416. * long 转 4个 HEX
    417. *
    418. * @param i
    419. * @return
    420. */
    421. public static String getHex_2formShort(short i) {
    422. String hex4 = "00000000" + Integer.toHexString(i);
    423. int length = hex4.length();
    424. return hex4.substring(length - 4, length);
    425. }
    426. /**
    427. *
    428. * long 转 4个 HEX
    429. *
    430. * @param i
    431. * @return
    432. */
    433. public static String getHex_1formShort(short i) {
    434. String hex4 = "00000000" + Integer.toHexString(i);
    435. int length = hex4.length();
    436. return hex4.substring(length - 2, length);
    437. }
    438. /**
    439. *
    440. * long 转 1个 HEX
    441. *
    442. * @param i
    443. * @return
    444. */
    445. public static String getHex_1formLong(byte i) {
    446. String hex4 = "00000000" + Integer.toHexString(i);
    447. int length = hex4.length();
    448. return hex4.substring(length - 2, length);
    449. }
    450. /**
    451. * 16进制直接转换成为字符串(无需Unicode解码)
    452. *
    453. * @param hexStr
    454. * @return
    455. */
    456. public static String hexStr_to_Str(String hexStr) {
    457. String str = "0123456789ABCDEF";
    458. char[] hexs = hexStr.toCharArray();
    459. byte[] bytes = new byte[hexStr.length() / 2];
    460. int n;
    461. for (int i = 0; i < bytes.length; i++) {
    462. n = str.indexOf(hexs[2 * i]) * 16;
    463. n += str.indexOf(hexs[2 * i + 1]);
    464. bytes[i] = (byte) (n & 0xff);
    465. }
    466. return new String(bytes);
    467. }
    468. //
    469. /**
    470. *
    471. * 判断一个字符串是否为url
    472. *
    473. * @param str
    474. * String 字符串
    475. *
    476. * @return boolean 是否为url
    477. *
    478. * @author peng1 chen
    479. *
    480. **/
    481. public static boolean isURL(String str) {
    482. // 转换为小写
    483. str = str.toLowerCase();
    484. String regex = "^((https|http|ftp|rtsp|mms|tcp)?://)" // https、http、ftp、rtsp、mms
    485. + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
    486. + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如:199.194.52.184
    487. + "|" // 允许IP和DOMAIN(域名)
    488. + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
    489. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
    490. + "[a-z]{2,6})" // first level domain- .com or .museum
    491. + "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
    492. + "((/?)|" // a slash isn't required if there is no file name
    493. + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
    494. return str.matches(regex);
    495. }
    496. /**
    497. * ID数组json串转List
    498. *
    499. * @param bindUserIds_req
    500. * @return
    501. */
    502. public static List getStringListByJsonStr(String bindUserIds_req) {
    503. List result = new ArrayList();
    504. try {
    505. if (bindUserIds_req != null) {
    506. result = JSON.parseArray(bindUserIds_req, String.class);
    507. }
    508. } catch (Exception e) {
    509. // TODO: handle exception
    510. }
    511. return result;
    512. }
    513. /**
    514. *
    515. *
    516. * @param args
    517. */
    518. public static void main(String[] args) {
    519. String str = "tcp://192.168.1.155";
    520. System.out.println(isURL(str));
    521. }
    522. public static boolean isNullOrEmpty(String s) {
    523. return s == null || s.isEmpty();
    524. }
    525. public static boolean isNotNullAndNotEmpty(String s) {
    526. return !isNullOrEmpty(s);
    527. }
    528. // public static String getHex_2formInt(Integer num) {
    529. // try {
    530. // return StringUtil.getHexString(MathUtil.intToBytes2(num));
    531. // }catch (Exception e){
    532. //
    533. // }
    534. // return null;
    535. // }
    536. }

    2、第二个

    1. package com.tigeriot.mqtt.util;
    2. import cn.hutool.core.util.RandomUtil;
    3. import cn.hutool.crypto.digest.DigestUtil;
    4. import com.tigeriot.mqtt.common.CodeConst;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.springframework.util.StringUtils;
    7. import java.security.SecureRandom;
    8. import java.util.ArrayList;
    9. import java.util.Arrays;
    10. import java.util.List;
    11. import java.util.Random;
    12. @Slf4j
    13. public class StringHexUtil {
    14. /**
    15. * 16进制字符串转字节数组
    16. * @param hexStr
    17. * @return
    18. */
    19. public static byte[] hexToByte(String hexStr){
    20. if(StringUtils.isEmpty(hexStr) ||!isHexStr(hexStr)){
    21. //判断失败
    22. return null;
    23. }
    24. return stringHexToBytes(hexStr);
    25. }
    26. /**
    27. * 实现字节数组转16进制字符串
    28. * @param bytes
    29. * @return
    30. */
    31. public static String byteToHex(byte[] bytes){
    32. StringBuilder hexString = new StringBuilder();
    33. for (byte b : bytes) {
    34. String hex = Integer.toHexString(b & 0xFF);
    35. if (hex.length() == 1) {
    36. hexString.append('0');
    37. }
    38. hexString.append(hex);
    39. }
    40. return hexString.toString();
    41. }
    42. /**
    43. * 判断是否合格16进制数
    44. * @param hexStr
    45. * @return
    46. */
    47. public static boolean isHexStr(String hexStr){
    48. String []s = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","a","b","c","d","e","f"};
    49. List list = Arrays.asList(s);
    50. char [] chars = hexStr.toCharArray();
    51. for (char c : chars) {
    52. if(!list.contains(String.valueOf(c))){
    53. return false;
    54. }
    55. }
    56. return true;
    57. }
    58. /**
    59. * 实现 16进制 字符串转字节数组
    60. * @param str
    61. * @return
    62. */
    63. public static byte[] stringHexToBytes(String str){
    64. char[] hexChars = str.toCharArray();
    65. byte[] bytes = new byte[hexChars.length / 2];
    66. for (int i = 0; i < bytes.length; i++) {
    67. int highNibble = Character.digit(hexChars[i * 2], 16);
    68. int lowNibble = Character.digit(hexChars[i * 2 + 1], 16);
    69. bytes[i] = (byte) ((highNibble << 4) | lowNibble);
    70. }
    71. return bytes;
    72. }
    73. /**
    74. * 判断字符串是否 为空串 为null 为空格
    75. * @param str
    76. * @return
    77. */
    78. public static boolean isNotBlank(String str) {
    79. return str != null && !str.isEmpty() && !str.trim().isEmpty();
    80. }
    81. /**
    82. * 验证 clientID 是否合法
    83. * @param clientID
    84. * @return
    85. */
    86. public static RV validateClientID(String clientID){
    87. if (!StringHexUtil.isNotBlank(clientID)){
    88. log.info("您的clientID不能为空格,空串,null:"+clientID);
    89. return RV.error(CodeConst.FAIL,"您的ClientID为空或空串",null);
    90. } else if (clientID.length()!=15) {
    91. log.info("您的clientID长度不为15:"+clientID);
    92. return RV.error(CodeConst.FAIL,"您的clientID长度不为15",null);
    93. } else if (!isNumeric(clientID)) {
    94. log.info("您的clientID不是数字:"+clientID);
    95. return RV.error(CodeConst.FAIL,"您的clientID不是数字",null);
    96. } else {
    97. return RV.ok(CodeConst.SUCCESS,"验证通过",null);
    98. }
    99. }
    100. /**
    101. * 生成 n 位随机 0-9的数
    102. * @param length
    103. * @return
    104. */
    105. public static String generateRandomNumber(int length) {
    106. Random random = new Random();
    107. StringBuilder sb = new StringBuilder(length);
    108. for (int i = 0; i < length; i++) {
    109. int digit = random.nextInt(10); // 生成0-9的随机数字
    110. sb.append(digit);
    111. }
    112. return sb.toString();
    113. }
    114. //随机20位字符串
    115. private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
    116. private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    117. private static final String DIGITS = "0123456789";
    118. private static final String ALL_CHARACTERS = LOWERCASE_CHARACTERS + UPPERCASE_CHARACTERS + DIGITS;
    119. private static final SecureRandom RANDOM = new SecureRandom();
    120. /**
    121. * 随机生成20位 包含大小写字母与数字的字符串
    122. * @param length
    123. * @return
    124. */
    125. public static String generateRandomString(int length) {
    126. StringBuilder randomString = new StringBuilder(length);
    127. // 确保至少包含一个小写字母、一个大写字母和一个数字字符
    128. randomString.append(LOWERCASE_CHARACTERS.charAt(RANDOM.nextInt(LOWERCASE_CHARACTERS.length())));
    129. randomString.append(UPPERCASE_CHARACTERS.charAt(RANDOM.nextInt(UPPERCASE_CHARACTERS.length())));
    130. randomString.append(DIGITS.charAt(RANDOM.nextInt(DIGITS.length())));
    131. // 生成剩余的字符
    132. for (int i = 3; i < length; i++) {
    133. randomString.append(ALL_CHARACTERS.charAt(RANDOM.nextInt(ALL_CHARACTERS.length())));
    134. }
    135. // 洗牌字符,使其顺序随机
    136. return shuffleString(randomString.toString());
    137. }
    138. /**
    139. * 函数用于洗牌字符串中的字符
    140. * @param input
    141. * @return
    142. */
    143. private static String shuffleString(String input) {
    144. char[] characters = input.toCharArray();
    145. for (int i = characters.length - 1; i > 0; i--) {
    146. int randomIndex = RANDOM.nextInt(i + 1);
    147. char temp = characters[i];
    148. characters[i] = characters[randomIndex];
    149. characters[randomIndex] = temp;
    150. }
    151. return new String(characters);
    152. }
    153. /**
    154. * 验证字符串是不是纯数字
    155. * @param str
    156. * @return
    157. */
    158. public static boolean isNumeric(String str) {
    159. if (str == null || str.length() == 0) {
    160. return false;
    161. }
    162. for (int i = 0; i < str.length(); i++) {
    163. if (!Character.isDigit(str.charAt(i))) {
    164. return false;
    165. }
    166. }
    167. return true;
    168. }
    169. /**
    170. * 将字符串实现SHA256加密算法
    171. * @param str
    172. */
    173. public static String strToSha256(String str){
    174. return DigestUtil.sha256Hex(str);
    175. }
    176. public static void main(String[] args) {
    177. System.out.println(generateRandomString(20));
    178. }
    179. }

    需要导入依赖

    1. <dependency>
    2. <groupId>cn.hutoolgroupId>
    3. <artifactId>hutool-allartifactId>
    4. <version>5.8.18version>
    5. dependency>

  • 相关阅读:
    二叉树的遍历
    什么是杜邦分析?杜邦分析法的公式及示例
    Vue模板语法上集(02)
    JS解混淆
    3. Apache HBase 为什么快?
    机械制造企业如何借助ERP系统,做好生产排产管理?
    如何使用 人像比对API
    cmake入门
    MySQL索引优化实战指南(InsCode AI 创作助手)
    内存管理——C++
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/134258727