Strings

@GwtCompatible
public final class Strings {
  private Strings() {}

  /**
   *若string为null,则返回空串;否则,返回自身
   */
  public static String nullToEmpty(@Nullable String string) {
    return (string == null) ? "" : string;
  }

  /**
   * 若string为null或者empty,都返回null;否则,返回自身
   */
  @Nullable
  public static String emptyToNull(@Nullable String string) {
    return isNullOrEmpty(string) ? null : string;
  }

  /**
   *当string为null或者为空时,返回true;否则,返回false
   *这里判断空串是通过length()==0,而java6中是isEmpty()
   */
  public static boolean isNullOrEmpty(@Nullable String string) {
    return string == null || string.length() == 0; // string.isEmpty() in Java 6
  }

  /**
   * 字符串填补
   * @param string 放在结果字符串的最后一部分
   * @param minLength 返回结果串应该具有的最小长度。可以为0或者负数,这样返回的是string本身
   * @param padChar 用于填补的字符,插入在string的前面,插入次数直到返回串的总长度达到minLength
   * @return the padded string
   */
  public static String padStart(String string, int minLength, char padChar) {
    checkNotNull(string);
    if (string.length() >= minLength) {
      return string;
    }
    StringBuilder sb = new StringBuilder(minLength);
    for (int i = string.length(); i < minLength; i++) {
      sb.append(padChar);
    }
    sb.append(string);
    return sb.toString();
  }

  /**
   * 与padStart类似,只不过padChar放到了string的后面
   */
  public static String padEnd(String string, int minLength, char padChar) {
    checkNotNull(string);
    if (string.length() >= minLength) {
      return string;
    }
    StringBuilder sb = new StringBuilder(minLength);
    sb.append(string);
    for (int i = string.length(); i < minLength; i++) {
      sb.append(padChar);
    }
    return sb.toString();
  }

  /**
   *字符串拷贝
   * @param string 非空字符串
   * @param count 重复次数,非负的
   * @return a string containing {@code string} repeated {@code count} times
   *     (the empty string if {@code count} is zero)
   * @throws IllegalArgumentException if {@code count} is negative
   */
  public static String repeat(String string, int count) {
    checkNotNull(string);  // eager for GWT.

    if (count <= 1) {
      checkArgument(count >= 0, "invalid count: %s", count);
      return (count == 0) ? "" : string;
    }

    final int len = string.length();
    final long longSize = (long) len * (long) count;
    final int size = (int) longSize;
  //如果最后得到的字符串过长,直接抛出异常
    if (size != longSize) {
      throw new ArrayIndexOutOfBoundsException(
          "Required array size too large: " + longSize);
    }

    final char[] array = new char[size];
  //直接调用系统的字符串拷贝函数:System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);

   string.getChars(0, len, array, 0);
   int n;
    for (n = len; n < size - n; n <<= 1) {
      System.arraycopy(array, 0, array, n, n);
    }
  //最后一次拷贝,拷贝长度是size-n
    System.arraycopy(array, 0, array, n, size - n);
    return new String(array);
  }

  /**
   *计算两个字符串的公共前缀
   */
  public static String commonPrefix(CharSequence a, CharSequence b) {
    checkNotNull(a);
    checkNotNull(b);
    int maxPrefixLength = Math.min(a.length(), b.length());
    int p = 0;
    while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
      p++;
    }
    if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
      p--;
    }
    return a.subSequence(0, p).toString();
  }

  /**
   * 同commonPrefix,只不过求的是公共后缀
   */
  public static String commonSuffix(CharSequence a, CharSequence b) {
    checkNotNull(a);
    checkNotNull(b);

    int maxSuffixLength = Math.min(a.length(), b.length());
    int s = 0;
    while (s < maxSuffixLength
        && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
      s++;
    }
    if (validSurrogatePairAt(a, a.length() - s - 1)
        || validSurrogatePairAt(b, b.length() - s - 1)) {
      s--;
    }
    return a.subSequence(a.length() - s, a.length()).toString();
  }

  @VisibleForTesting
  static boolean validSurrogatePairAt(CharSequence string, int index) {
    return index >= 0 && index <= (string.length() - 2)
        && Character.isHighSurrogate(string.charAt(index))
        && Character.isLowSurrogate(string.charAt(index + 1));
  }
}
时间: 2024-11-06 11:57:10

Strings的相关文章

43. Multiply Strings

1. 问题描述 Given two numbers represented as strings, return multiplication of the numbers as a string.Note:The numbers can be arbitrarily large and are non-negative.Converting the input string to integer is NOT allowed.You should NOT use internal librar

Multiply Strings

package cn.edu.xidian.sselab;/** * title:Multiply Strings * content: * Given two numbers represented as strings, return multiplication of the numbers as a string. * Note: The numbers can be arbitrarily large and are non-negative. * 读已知条件可以,两个String转换

leetcode笔记:Isomorphic Strings

一.题目描述 Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of chara

LeetCode:Isomorphic Strings

1.题目名称 Isomorphic Strings(同构的字符串) 2.题目地址 https://leetcode.com/problems/isomorphic-strings/ 3.题目内容 英文: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurre

poj 2406 Power Strings KMP

Description Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative inte

go语言学习 strings常用函数

strings包中的函数用法 参考链接http://studygolang.com/articles/88 1.strings.replace() 函数原型 func Replace(str1, old, str2, n int) string //old是str1中的字符串,用str2替换str1中的old,一共替换n个.如果n<0,则全部替换 fmt.Println(strings.Replace("tet tet tet", "e", "es&

strings用法小记

By francis_hao    Feb 14,2017 打印文件中可打印字符,每个序列至少四(可配置)个字符长.主要用于显示非文本文件 概述 选项解释 -a --all - 扫描整个文件,不管那些段是否被加载或初始化,一般此项是默认的,除非程序被配置成-d的模式 -d --data 只打印初始化过或加载过的部分,此项可以减少一些垃圾数据. -f --print-file-name 在打印字符之前打印文件名 -min-len -n min-len --bytes=min-len 指定打印的最短

Power Strings(KMP)

Power Strings Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 45008   Accepted: 18794 Description Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "

[shiro] Wildcard string cannot be null or empty. Make sure permission strings are properly formatted.

访问某页面时,出现了这个异常: java.lang.IllegalArgumentException: Wildcard string cannot be null or empty. Make sure permission strings are properly formatted. at org.apache.shiro.authz.permission.WildcardPermission.setParts(WildcardPermission.java:154) at org.apa

LeetCode-Isomorphic Strings

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters.