Files
py_enjoy/kit/StrKit.py
2026-02-27 14:37:10 +08:00

140 lines
4.0 KiB
Python

#!/usr/bin/env python3.9
# -*- coding: utf-8 -*-
"""
JFinal StrKit - String Utilities
"""
class StrKit:
"""String utility class"""
@staticmethod
def first_char_to_lower_case(s: str) -> str:
"""首字母变小写"""
if not s:
return s
first_char = s[0]
if 'A' <= first_char <= 'Z':
arr = list(s)
arr[0] = chr(ord(arr[0]) + ord('a') - ord('A'))
return ''.join(arr)
return s
@staticmethod
def first_char_to_upper_case(s: str) -> str:
"""首字母变大写"""
if not s:
return s
first_char = s[0]
if 'a' <= first_char <= 'z':
arr = list(s)
arr[0] = chr(ord(arr[0]) - (ord('a') - ord('A')))
return ''.join(arr)
return s
@staticmethod
def is_blank(s: str) -> bool:
"""字符串为 null 或者内部字符全部为 ' ' '\\t' '\\n' '\\r' 这四类字符时返回 true"""
if s is None:
return True
for char in s:
if char > ' ':
return False
return True
@staticmethod
def not_blank(s: str) -> bool:
return not StrKit.is_blank(s)
@staticmethod
def not_blank(*strings) -> bool:
if strings is None or len(strings) == 0:
return False
for s in strings:
if StrKit.is_blank(s):
return False
return True
@staticmethod
def has_blank(*strings) -> bool:
if strings is None or len(strings) == 0:
return True
for s in strings:
if StrKit.is_blank(s):
return True
return False
@staticmethod
def not_null(*paras) -> bool:
if paras is None:
return False
for obj in paras:
if obj is None:
return False
return True
@staticmethod
def default_if_blank(s: str, default_value: str) -> str:
return default_value if StrKit.is_blank(s) else s
@staticmethod
def to_camel_case(s: str) -> str:
"""将包含下划线字符 '_' 的字符串转换成驼峰格式,不包含下划线则原样返回"""
return StrKit._to_camel_case(s, False)
@staticmethod
def _to_camel_case(s: str, to_lower_case_anyway: bool) -> str:
length = len(s)
if length <= 1:
return s
buf = []
index = 0
i = 0
while i < length:
ch = s[i]
if ch == '_':
i += 1
if i < length:
ch = s[i]
if index == 0:
buf.append(chr(ord(ch) + 32) if 'A' <= ch <= 'Z' else ch)
else:
buf.append(chr(ord(ch) - 32) if 'a' <= ch <= 'z' else ch)
index += 1
else:
buf.append(chr(ord(ch) + 32) if 'A' <= ch <= 'Z' else ch)
index += 1
i += 1
if to_lower_case_anyway:
return ''.join(buf[:index])
return s if i == index else ''.join(buf[:index])
@staticmethod
def join(string_array, separator: str = '') -> str:
"""Join string array"""
if not string_array:
return ''
if separator:
return separator.join(string_array)
return ''.join(string_array)
@staticmethod
def slow_equals(a: str, b: str) -> bool:
"""Timing-safe string comparison"""
from .HashKit import HashKit
a_bytes = a.encode('utf-8') if a else None
b_bytes = b.encode('utf-8') if b else None
return HashKit.slow_equals(a_bytes, b_bytes)
@staticmethod
def equals(a: str, b: str) -> bool:
return a is None if b is None else a == b
@staticmethod
def get_random_uuid() -> str:
"""Generate random UUID without dashes"""
import uuid
return uuid.uuid4().hex