StringUtils.java 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
package cn.fw.dalaran.common.utils;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 *
 * @author: kurisu
 * @version: 1.0
 */
public final class StringUtils {

    /**
     * 空字符串
     */
    public static final String EMPTY = "";
    /**
     * 特殊字符正则表达式
     */
    public static final String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";

    public static final String regNo = "^[-\\+]?[\\d]*$";

    public static final String tagsPattern = "#[^#](['\"]?[^ '\"]+['\"]?)";

    private StringUtils() {
    }

    /**
     * 首字母小写
     *
     * @param s String
     * @return String
     */
    public static String firstCharLowerCase(String s) {
        if (isValid(s)) {
            return s.substring(0, 1).toLowerCase() + s.substring(1);
        }
        return s;
    }

    /**
     * 删除前缀
     *
     * @param s
     * @param prefix
     * @return
     */
    public static String removePrefix(String s, String prefix) {
        int index = s.indexOf(prefix);
        return index == 0 ? s.substring(prefix.length()) : s;
    }

    /**
     * 删除后缀
     *
     * @param s
     * @param suffix
     * @return
     */
    public static String removeSuffix(String s, String suffix) {
        return s.endsWith(suffix) ? s.substring(0, s.length() - suffix.length()) : s;
    }

    /**
     * 首字母大写
     *
     * @param s String
     * @return String
     */
    public static String firstCharUpperCase(String s) {
        if (isValid(s)) {
            return s.substring(0, 1).toUpperCase() + s.substring(1);
        }
        return s;
    }

    /**
     * 检查对象是否有效 obj != null && obj.toString().length() > 0
     *
     * @param obj
     * @return boolean
     */
    public static boolean isValid(Object obj) {
        return obj != null && obj.toString().length() > 0;
    }

    /**
     * 是否是空的
     *
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        return obj == null || obj.toString().length() == 0;
    }

    /**
     * 是否是数字
     *
     * @param obj
     * @return
     */
    public static boolean isNumber(Object obj) {
        if (isEmpty(obj)) {
            return false;
        }
        Pattern compile = Pattern.compile(regNo);
        return compile.matcher(obj.toString()).matches();
    }

    /**
     * 转化为String对象
     *
     * @param obj
     * @return boolean
     */
    public static String asString(Object obj) {
        return obj != null ? obj.toString() : "";
    }

    /**
     * 返回其中一个有效的对象 value != null && value.toString().length() > 0
     *
     * @param values
     */
    public static String tryThese(Object... values) {
        for (int i = 0; i < values.length; i++) {
            String value = StringUtils.asString(values[i]);
            if (!value.isEmpty()) {
                return value;
            }
        }
        return "";
    }

    /**
     * EL表达式提供的定义方法
     *
     * @param v1
     * @param v2
     * @return
     */
    public static String tryThese(String v1, String v2) {
        return tryThese(new Object[]{v1, v2});
    }

    /**
     * 连接字符串
     *
     * @param list
     * @param split
     * @return 字符串
     */
    public static <T> String join(T[] list, String split) {
        return join(list, split, "");
    }

    /**
     * 连接字符串
     *
     * @param list
     * @param split
     * @return 字符串
     */
    public static <T> String join(T[] list, String split, String wrap) {
        if (list == null) {
            return null;
        }
        StringBuilder s = new StringBuilder(128);
        for (int i = 0; i < list.length; i++) {
            if (i > 0) {
                s.append(split);
            }
            s.append(wrap + list[i] + wrap);
        }
        return s.toString();
    }

    /**
     * 连接
     *
     * @param list
     * @param split
     * @param wrap
     * @return
     */
    public static <T> String join(List<T> list, String split, String wrap) {
        return join(list.toArray(), split, wrap);
    }

    /**
     * 连接字符串
     *
     * @param list
     * @param split
     * @return 字符串
     */
    public static String join(List<?> list, String split) {
        return join(list.toArray(), split);
    }

    /**
     * 包裹字符串 id:12, {, } 输出 {id:12}
     *
     * @param input 输入串
     * @param begin {
     * @param end   }
     * @return String
     */
    public static String wrap(String begin, String input, String end) {
        if (!input.startsWith(begin)) {
            input = begin + input;
        }
        if (!input.endsWith(end)) {
            input = input + end;
        }
        return input;
    }

    /**
     * 取得匹配的字符串
     *
     * @param input
     * @param regex
     * @return
     */
    public static List<String> matchs(String input, String regex) {
        return matchs(input, regex, 0);
    }

    /**
     * 取得匹配的字符串
     *
     * @param input
     * @param regex
     * @return
     */
    public static List<String> matchs(String input, String regex, int group) {
        List<String> matches = new ArrayList<String>();
        if (isEmpty(input)) {
            return matches;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(input);
        while (match.find()) {
            matches.add(match.group(group));
        }
        return matches;
    }

    /**
     * 找到匹配的第一个字符串
     *
     * @param input
     * @param regex
     * @param group
     * @return
     */
    public static String matchFirst(String input, String regex, int group) {
        List<String> matches = matchs(input, regex, group);
        return matches.isEmpty() ? null : matches.get(0);
    }

    /**
     * 截取指定长度字符串
     *
     * @return
     */
    public static String getShorterString(String str, int maxLength) {
        return getShorterString(str, "...", maxLength);
    }

    /**
     * 截取指定长度字符串
     *
     * @param input
     * @param tail
     * @param length
     * @return
     */
    public static String getShorterString(String input, String tail, int length) {
        tail = isValid(tail) ? tail : "";
        StringBuffer buffer = new StringBuffer(512);
        try {
            int len = input.getBytes("GBK").length;
            if (len > length) {
                int ln = 0;
                for (int i = 0; ln < length; i++) {
                    String temp = input.substring(i, i + 1);
                    if (temp.getBytes("GBK").length == 2) {
                        ln += 2;
                    } else {
                        ln++;
                    }

                    if (ln <= length) {
                        buffer.append(temp);
                    }
                }
            } else {
                return input;
            }
            buffer.append(tail);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 取得GBK编码
     *
     * @return
     */
    public static String getBytesString(String input, String code) {
        try {
            byte[] b = input.getBytes(code);
            return Arrays.toString(b);
        } catch (UnsupportedEncodingException e) {
            return String.valueOf(code.hashCode());
        }
    }

    /**
     * 转换格式 CUST_INFO_ID - > custInfoId
     *
     * @param input
     * @return
     */
    public static String getFieldString(String input) {
        if (input == null) {
            return null;
        }
        String field = input.toLowerCase();
        String[] values = field.split("\\_");
        StringBuffer b = new StringBuffer(input.length());
        for (int i = 0; i < values.length; i++) {
            if (i == 0) {
                b.append(values[i]);
            } else {
                b.append(firstCharUpperCase(values[i]));
            }
        }
        return b.toString();
    }

    /**
     * 转换格式 CUST_INFO_ID - > custInfoId
     *
     * @param columnName
     * @return
     */
    public static String toFieldName(String columnName) {
        return getFieldString(columnName);
    }

    /**
     * 转换格式 custInfoId - > CUST_INFO_ID
     *
     * @param field
     * @return
     */
    public static String toColumnName(String field) {
        if (field == null) {
            return null;
        }
        StringBuffer b = new StringBuffer(field.length() + 3);
        for (int i = 0; i < field.length(); i++) {
            Character char1 = field.charAt(i);
            if (Character.isUpperCase(char1) && i != 0) {
                b.append("_");
            }
            b.append(char1);
        }
        return b.toString();
    }

    /**
     * 转化为JSON值
     *
     * @param value
     * @return
     * @throws IOException
     */
    public static String toJsonValue(Object value) throws IOException {
        if (value instanceof Number) {
            return value.toString();
        } else {
            return "'" + value.toString() + "'";
        }
    }

    /**
     * 字符串转化为UUID
     *
     * @param value
     * @return
     */
    public static String toUUID(String value) {
        if (value == null) {
            throw new RuntimeException("value is null!");
        }
        return UUID.nameUUIDFromBytes(value.getBytes()).toString();
    }

    /**
     * 获取Style样式中样式的值
     *
     * @param styleString
     * @param styleName
     * @return 相应的值
     */
    public static String getStyleValue(String styleString, String styleName) {
        String[] styles = styleString.split(";");
        for (int i = 0; i < styles.length; i++) {
            String tempValue = styles[i].trim();
            if (tempValue.startsWith(styleName)) {
                String[] style = tempValue.split(":");
                return style[1];
            }
        }
        return "";
    }

    /**
     * 生成重复次字符
     *
     * @param charactor
     * @param repeat
     * @return
     */
    public static String getRepeat(String charactor, int repeat) {
        return repeat(charactor, repeat, "");
    }

    /**
     * 生成重复次字符
     *
     * @param charactor
     * @param repeat
     * @return
     */
    public static String repeat(String charactor, int repeat, String split) {
        StringBuilder s = new StringBuilder(charactor.length() * repeat);
        for (int i = 0; i < repeat; i++) {
            if (i != 0) {
                s.append(split != null ? split : "");
            }
            s.append(charactor);
        }
        return s.toString();
    }

    /**
     * 取得长度
     *
     * @param text
     * @return
     */
    public static int length(String text) {
        int len = text.length();
        try {
            len = text.getBytes("GBK").length;//SQLServer数据库用的GBK编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return len;
    }

    /**
     * 字符串替换函数
     *
     * @param data 字符串
     * @param data from  旧值
     * @param to   from  新值
     */
    public static String replaceString(String data, String from, String to) {
        StringBuffer buf = new StringBuffer(data.length());
        int pos = -1;
        int i = 0;
        while ((pos = data.indexOf(from, i)) != -1) {
            buf.append(data.substring(i, pos)).append(to);
            i = pos + from.length();
        }
        buf.append(data.substring(i));
        return buf.toString();
    }

    /**
     * 转义特殊字符
     *
     * @param s
     * @return
     */
    public static String escapeQueryChars(String s) {
        if (StringUtils.isEmpty(s)) {
            return s;
        }
        StringBuilder sb = new StringBuilder();
        //查询字符串一般不会太长,挨个遍历也花费不了多少时间
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')'
                    || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"'
                    || c == '{' || c == '}' || c == '~' || c == '*' || c == '?'
                    || c == '|' || c == '&' || c == ';' || c == '/' || c == '.'
                    || c == '$' || c == '%' || c == '<' || c == '>' || Character.isWhitespace(c)) {
                sb.append('\\');
            }
            sb.append(c);
        }
        return sb.toString();
    }


    /**
     * 获取默认值
     *
     * @param str
     * @param defaultStr
     * @return
     */
    public static String getStrWithDefault(CharSequence str, String defaultStr) {
        if (isEmpty(defaultStr)) {
            defaultStr = "";
        }
        if (isEmpty(str)) {
            return defaultStr;
        }
        return str.toString();
    }

    public static void main(String[] args) {
        System.out.println(toUUID("1"));
        System.out.println(removePrefix("abcd123", "ab"));
        System.out.println(removeSuffix("abcd123", "123"));
        System.out.println(toColumnName("usernameId"));
        System.out.println(getFieldString("user_name_id"));
        System.out.println(repeat("?", 10, ","));
        length("AAA中国()111222bb");
    }
}