[一篇看懂] string的各种操作

1. 找

1.1. 找字符或串(最后一次)

  • lastIndexOf(int ch)
    • this.codePointAt(k) == ch
    • 以Unicode代码为单位
  • lastIndexOf(int ch, int fromIndex)
    • 从指定的索引开始向后搜索
  • lastIndexOf(String str)
    • 找子串
  • lastIndexOf(String str, int fromIndex)
    • 从指定的索引开始向后搜索

1.2. 找字符或串(第一次)

  • indexOf(String str, int fromIndex)
  • indexOf(String str)
  • indexOf(int ch, int fromIndex)
  • indexOf(int ch)

2. 合并

  • join(CharSequence delimiter, CharSequence… elements)
   String message = String.join("-", "Java", "is", "cool");
     // message returned is: "Java-is-cool"
  • join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
    • 使用迭代器
     List<String> strings = new LinkedList<>();
     strings.add("Java");strings.add("is");
     strings.add("cool");
     String message = String.join(" ", strings);
     //message returned is: "Java is cool"

3. 访问

  • charAt(int index)

4. 修改

  • replaceFirst(String regex, String replacement)
  • replaceAll(String regex, String replacement)
  • replace(CharSequence target, CharSequence replacement)
  • replace(char oldChar, char newChar)
  • trim() :删前后空格
  • toUpperCase() :所有字母大写
  • toLowerCase() :所有字母小写
  • subSequence() :substring(int beginIndex),substring(int beginIndex, int endIndex)
    • 一个参数i类型: 删除前i个字符,返回剩余字符
    • 两个参数类型: 返回两参数之间的字符(注意: 后者参数位置处的字符不包含)
  • split(String regex) 分隔

5. 返回 数组

5.1. 字符数组

  • toCharArray() :返回对应的字符数组

5.2. byte数组

  • byte[] getBytes(String charsetName)
    • 使用命名的字符集将此String编码为字节序列,将结果存储到新的字节数组中。
  • byte[] getBytes(Charset charset)
    • 使用给定的charset将该String编码为一个字节序列,将结果存储到新的字节数组中。
  • byte[] getBytes()
    • 使用平台的默认字符集

6. 比较

  • int compareTo(String anotherString)
    • 字符串比较: 根据Unicode值
    • 返回差值this.charAt(k)-anotherString.charAt(k)
    • 如果没有它们不同的索引位置,则较短的字符串按字典顺序位于较长的字符串之前。 在这种情况下, compareTo返回字符串长度的差异
  • compareToIgnoreCase(String str)
    • 忽略大小写
  • startsWith(String prefix) : 测试此字符串是否以指定的前缀开头
  • startsWith(String prefix, int toffset) :测试在指定索引处开始的此字符串的子字符串是否以指定的前缀开头。
  • endsWith(String suffix)
    • 测试此字符串是否以指定的后缀结尾。
  • equals(Object anObject)
  • equalsIgnoreCase(String anotherString)
    • 忽略大小写
  • regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
    • ignoreCase :如果 true , true时忽略大小写。
    • toffset 该字符串 toffset的起始偏移量。
    • other 字符串参数。
    • ooffset 字符串参数 ooffset的起始偏移量。
    • len 要比较的字符数。
  • regionMatches(int toffset, String other, int ooffset, int len)

7. 值转化

  • 各种valueOf()
    • 返回 string类型

8. 返回Unicode值

  • codePointAt(int index)
  • codePointBefore(int index)
  • codePointCount(int beginIndex, int endIndex)
    • 返回此 String指定文本范围内的Unicode代码点数。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值