【Java】常用方法

遇到了就写在这里

1 String 类

char charAt(int index)

返回指定索引处的 char 值

String concat(String str)

将指定的字符串连接到此字符串的末尾

String substring(int beginIndex)
返回一个字符串,该字符串是此字符串的子字符串。


String substring(int beginIndex, int endIndex)
返回一个字符串,该字符串是此字符串的子字符串,注意包括起始索引,不包括结束索引

String[] split(String regex)

字符串拆分,regex 为正则表达式

boolean equalsIgnoreCase(String anotherString)

忽略大小写的字符串匹配

String valueOf()

转换成string,后面写要转换的形式,任何形式

format("%.2f", n)

保留两位小数

2 StringBuffer 和 StringBuilder 类

声明:

StringBuffer rev = new StringBuffer("abc");

对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类

由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类

public StringBuffer append(String s)
将指定的字符串追加到此字符序列

public StringBuffer reverse()
将此字符序列用其反转形式取代

replace(int start, int end, String str)
使用给定 String 中的字符替换此序列的子字符串中的字符

3 Arrays 类

以 int 为例

copyOf(int[] original, int newLength)

复制数组

copyOfRange(int[] original, int from, int to)

复制数组,指定了索引范围,包括 from,不包括 to

boolean equals(int[] a, int[] a2)

比较两个数组是否相等

sort(int[] a)

排序

String toString(int[] a)

转成字符串并返回

4 Integer 类

String toString()

返回String表示此对象Integer的价值

static String toString(int i)

转为字符串

进制转换:

public static String toBinaryString(int i)

十进制转换为二进制

public static String toOctalString(int i)

十进制数转换成八进制数

public static String toHexString(int i)

十进制转换成十六进制数

public static String toString(int i , int radix))

十进制数转换成 radix 进制数

public static int parseInt(String s , int radix)

radix 进制数转换成十进制数

5 日期类

5.1 LocalDate

now()

静态方法,获取当前日期

of(int year, int month, int dayOfMonth)

静态方法,根据年、月、日创建一个 LocalDate 实例

getYear()getMonthValue()getDayOfMonth()

获取年、月、日

plusDays(long daysToAdd)minusDays(long daysToSubtract)

添加/减去指定天数,返回新的 LocalDate 对象

plusMonths(long monthsToAdd)minusMonths(long monthsToSubtract)

添加/减去指定月数,返回新的 LocalDate 对象

plusYears(long yearsToAdd)minusYears(long yearsToSubtract)

添加/减去指定年数,返回新的 LocalDate 对象

isEqual(LocalDate other)isBefore(LocalDate other)isAfter(LocalDate other)

比较日期的相等性、先后顺序

isLeapYear()

判断是否为闰年

parse(CharSequence text, DateTimeFormatter formatter)

解析字符串为 LocalDate 对象

如:

LocalDate ld = LocalDate.parse("2023-12-31")

DateTimeFormatter

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

按规定的格式进行截取

LocalDate ld = LocalDate.parse(date, dateTimeFormatter);

如:

20240328
进行截取

ld 就是"2024-03-28"

5.2 LocalTime

几乎和 LocalDate 一致

5.3 LocalDateTime

注意 parse 用法

LocalDateTime parsedDateTime = LocalDateTime.parse("2024-03-28T15:30:00");

5.4 chronoUnit

between(Temporal startInclusive, Temporal endExclusive)

计算两个时间点之间的时间单位数量,例如计算两个日期之间的天数、小时数等。

例如:

ChronoUnit.DAYS.between(startld, ld)返回天数

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值