Java 操作字符串方法

遍历字符串

统计字符串中元音个数

public static int countVowels(String input) {
    return input.replaceAll("[^aeiouAEIOU]", "").length();
}

public static int countVowels(String input) {
    return input.length() - input.replaceAll("[aeiouAEIOU]", "").length();
}

统计字符个数

/**
 * 统计字符个数 (区分大小写)
 */
public static int countChars(String str, char targetChar) {
    char[] chars = str.toCharArray();
    int count = 0;
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == targetChar) {
            count++;
        }
    }
    return count;
}

public static int countChars2(String str, char c) {
    return (int)IntStream.range(0, str.length()).map(str::charAt).filter(a -> a == c).count();
}
--------------------------------------------------------------------------------
/**
 * 统计字符个数 (忽略大小写)
 */
public static int countCharsIgnoreCase(String str, char targetChar) {
    char[] chars = str.toLowerCase(Locale.ROOT).toCharArray();
    char c = Character.toLowerCase(targetChar);
    int count = 0;
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == c) {
            count++;
        }
    }
    return count;
}

public static int countCharsIgnoreCase2(String str, char ch) {
    char[] chars = str.toLowerCase(Locale.ROOT).toCharArray();
    char c = Character.toLowerCase(ch);
    return (int)IntStream.range(0, str.length()).map(i->chars[i]).filter(a -> a == c).count();
}
--------------------------------------------------------------------------------
/**
 * 统计符合条件字符个数 (区分大小写)
 */
 public static int countChars2(String str) {
    return (int)IntStream.range(0, str.length()).map(str::charAt).filter(a -> 'a' <= a && a <= 'z').count();
}
countChars2("asdzAZ")4

检查字符串字符全为数字

public static boolean isNumeric(final String input) {
    return IntStream.range(0, input.length()).allMatch(i -> Character.isDigit(input.charAt(i)));
}

命名加工

字符串大小写转化

Ascii.toUpperCase("aaaBBaa"));  // AAABBAA
Ascii.toLowerCase("AAAaaAA"));  // aaaaaaa

"aaaBBaa".toUpperCase(Locale.ROOT));  // AAABBAA
"AAAbbAA".toLowerCase(Locale.ROOT));  // aaabbaa
/**
 * 字符串大小写转化
 * 大写字母多 → 全转大写
 * 小写字母多 → 全转小写
 * 大小写一样多 → 不转化保留当前字符串
 */
public static String caseConver(String str) {
    int lower = str.length() - str.replaceAll("[a-z]", "").length(); // 统计大写字母个数
    int upper = str.length() - str.replaceAll("[A-Z]", "").length(); // 统计小写字母个数
    
    if (lower > upper) {
        return str.toLowerCase(Locale.ROOT);
    } else if (lower < upper) {
        return str.toUpperCase(Locale.ROOT);
    } else {
        return str;
    }
}

caseConver("ABCdefgh")); // abcdefgh
caseConver("ABCDefgh")); // ABCDefgh
caseConver("ABCDEfgh")); // ABCDEFGH

判断字符串是否为大/小写

# 判断字符串是否为小写
public static boolean isLowerCase(String input) {
    return Objects.equals(input, input.toLowerCase());
}

# 判断字符串是否为大写
public static boolean isUpperCase(String input) {
    return Objects.equals(input, input.toUpperCase());
}

将字符串首字母大写

public static String capitalize(String input, boolean lowerRest) {
    return input.substring(0, 1).toUpperCase() + (lowerRest ? input.substring(1, input.length()).toLowerCase() : input.substring(1, input.length()));
}

将字符串中每个单词的首字母大写

public static String capitalizeEveryWord(final String input) {
    return Pattern.compile("\\b(?=\\w)").splitAsStream(input).map(w -> capitalize(w, false)).collect(Collectors.joining());
}
"hello worldD"Hello WorldD

驼峰→蛇形

public static String camelCase2Snake(String input, String separator) {
    return input.replaceAll("([^A-Z])([A-Z])", "$1" + separator + "$2").toLowerCase();
}
camelCase2Snake("helloWorldHaha", "-") → hello-world-haha

驼峰间→插入separator

public static String insertSeparator2CamelCase(String input, String separator) {
    return input.replaceAll("([^A-Z])([A-Z])", "$1" + separator + "$2");
}
insertSeparator2CamelCase("helloWorldHaha", "-"); → hello-World-Haha

字符串驼峰和下划线格式互转

字符串拆分

将多行字符串拆分为行数组

public static String[] splitLines(String input) {
    return input.split("\\r?\\n");
}

特殊类型字符串

回文子串

NC17 最长回文子串

/**
 * 判断子串是不是回文子串
 */
public static boolean isPalindrome(String s) {
        // null, ""(空字符串场景), "a"(单字符字符串场景)
        if (s == null || s.length() <= 1) {
            return true;
        }

        // 知识点1: [0,arr.length/2)为数组对称部分左一半
        // abcba  奇数时 5/2=2 范围for (int i = 0; i < 2; i++) [0 1] ② 3 4
        // abccba 偶数时 6/2=3 范围for (int i = 0; i < 3; i++) [0 1 2] ③ 4 5
        int strLength = s.length();
        for (int i = 0; i < strLength / 2; i++) {

            // 知识点2: 数组折叠对应下标相加为length - 1
            if (s.charAt(i) != s.charAt(strLength - 1 - i)) // 不相等
                return false;
        }

        // 知识点3: 基于找事思路,存在不符合条件的就算失败,不然就算通过
        return true;
}

/**
 * 判断子串是不是回文子串
 */
public static boolean isPalindrome(String input) {
	# \W表示非字母数字下划线,[\W_]表示除了字母数字以外的字符
    String s = input.toLowerCase().replaceAll("[\\W_]", "");
    return Objects.equals(s, new StringBuilder(s).reverse().toString());
}


isPalindrome("abccba")); // true
isPalindrome("aa"));     // true
isPalindrome("abc"));    // false
isPalindrome("ab"));     // false
isPalindrome("a"));      // true
isPalindrome(""));       // true
isPalindrome("  "));     // true

[中等] HJ27.查找兄弟单词

/**
 * 定义一个单词的 "兄弟单词" 为:
 * 交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。且兄弟单词要求和原来的单词不同。
 * 例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。
 */
public static boolean isBro(String str, String target) {
    // 长度不等指定不为兄弟单词
    if (str.length() != target.length()) {
        return false;
    }
    // 兄弟单词要求和原来的单词不同
    if (str.equals(target)) {
        return false;
    }
    
    char[] chars = str.toCharArray();
    Arrays.sort(chars);
    
    char[] targets = target.toCharArray();
    Arrays.sort(targets);
    
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] != targets[i]) {
            return false;
        }
    }
    
    return true;
}

isBro("abd","abd"));   // false
isBro("",""));         // false
isBro("abd","aswd"));  // false
isBro("abd",""));      // false
isBro("abd","ade"));   // false
isBro("abc","acb"));   // true 

字母+偏移量+模来模拟加密算法

/**
 * 字符串ASC码+偏移量实现加密
 */
public static char tran(char c, int offset) {
    int newChar = c + offset;
    
    if (newChar < 'a') {
        // <a 给个默认值
        return 'a';
    } else if ('a' <= newChar && newChar <= 'z') {
        // a-z范围内,直接收集
        return (char) newChar;
    } else {
        // >z 取模算结果
        return (char) ((newChar - 'a') % 26 + 'a');
    }
}

System.out.println((char) ('a' + (97 - 'a') % 26)); // a	97	-	97	=	0
System.out.println((char) ('a' + (98 - 'a') % 26)); // b	98	-	97	=	1
System.out.println((char) ('a' + (99 - 'a') % 26)); // c	99	-	97	=	2
System.out.println((char) ('a' + (100 - 'a') % 26));// d	100	-	97	=	3
System.out.println((char) ('a' + (101 - 'a') % 26));// e	101	-	97	=	4
System.out.println((char) ('a' + (102 - 'a') % 26));// f	102	-	97	=	5
System.out.println((char) ('a' + (103 - 'a') % 26));// g	103	-	97	=	6
System.out.println((char) ('a' + (104 - 'a') % 26));// h	104	-	97	=	7
System.out.println((char) ('a' + (105 - 'a') % 26));// i	105	-	97	=	8
System.out.println((char) ('a' + (106 - 'a') % 26));// j	106	-	97	=	9
System.out.println((char) ('a' + (107 - 'a') % 26));// k	107	-	97	=	10
System.out.println((char) ('a' + (108 - 'a') % 26));// l	108	-	97	=	11
System.out.println((char) ('a' + (109 - 'a') % 26));// m	109	-	97	=	12
System.out.println((char) ('a' + (110 - 'a') % 26));// n	110	-	97	=	13
System.out.println((char) ('a' + (111 - 'a') % 26));// o	111	-	97	=	14
System.out.println((char) ('a' + (112 - 'a') % 26));// p	112	-	97	=	15
System.out.println((char) ('a' + (113 - 'a') % 26));// q	113	-	97	=	16
System.out.println((char) ('a' + (114 - 'a') % 26));// r	114	-	97	=	17
System.out.println((char) ('a' + (115 - 'a') % 26));// s	115	-	97	=	18
System.out.println((char) ('a' + (116 - 'a') % 26));// t	116	-	97	=	19
System.out.println((char) ('a' + (117 - 'a') % 26));// u	117	-	97	=	20
System.out.println((char) ('a' + (118 - 'a') % 26));// v	118	-	97	=	21
System.out.println((char) ('a' + (119 - 'a') % 26));// w	119	-	97	=	22
System.out.println((char) ('a' + (120 - 'a') % 26));// x	120	-	97	=	23
System.out.println((char) ('a' + (121 - 'a') % 26));// y	121	-	97	=	24
System.out.println((char) ('a' + (122 - 'a') % 26));// z	122	-	97	=	25
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值