【成长积累3——替换字符串中的空格】

package com.example.algorithm.findnumber;

/**
 * 将一个字符串中的空格替换成"%20"
 *
 * @author tengxiang
 * @date 2020/5/14
 * @since 1.0
 */
public class ReplaceBlank4 {

    /**
     * 解法一:使用StringBuffer
     * @param str
     * @return
     */
    public static String replaceBlank(String str){
        if(str == null){
            return null;
        }
        StringBuffer s = new StringBuffer();
        for(int i = 0 ; i < str.length() ; i++){
            if(str.charAt(i) == ' '){
                s.append("%20");
            }else{
                s.append(str.charAt(i));
            }
        }
        return s.toString();
    }

    /**
     * 解法二:使用StringBuilder
     * @param str
     * @return
     */
    public static String replaceBlank2(String str){
        if(str == null){
            return null;
        }
        StringBuilder s = new StringBuilder();
        for(int i = 0 ; i < str.length() ; i++){
            if(" ".equals(String.valueOf(str.charAt(i)))){
                s.append("%20");
            }else{
                s.append(str.charAt(i));
            }
        }
        return new String(s);
    }

    /**
     * 解法三:从后往前复制
     * @param str
     * @return
     */
    public static String replaceBlank3(String str){
        if(str == null){
            return null;
        }

        int length = str.length();
        //统计空格数
        int blankNum = 0;
        for(int i = 0; i < length ; i++){
            if(str.charAt(i) == ' '){
                blankNum++;
            }
        }

        int newLength = length + blankNum * 2;
        char[] newStr = new char[newLength];
        int index = newLength - 1;
        for(int i = length - 1 ; i >= 0 ; i--){
            if(str.charAt(i) == ' '){
                newStr[index--] = '0';
                newStr[index--] = '2';
                newStr[index--] = '%';
            }else{
                newStr[index--] = str.charAt(i);
            }
        }
        return new String(newStr);
    }

    public static void main(String[] args) {
        System.out.println(replaceBlank3("a b c "));
    }

}

 

### Java 中替换字符串的方法 在 Java 编程语言中,可以通过多种方式实现字符串替换操作。以下是几种常见的方法及其功能描述: #### 1. 使用 `String` 类中的 `replace(CharSequence target, CharSequence replacement)` 方法 此方法用于将指定字符序列的所有匹配项替换为新的字符序列。它不会区分正则表达式模式[^2]。 ```java public class ReplaceExample { public static void main(String[] args) { String original = "hello world"; String replaced = original.replace("world", "Java"); System.out.println(replaced); // 输出: hello Java } } ``` #### 2. 使用 `replaceAll(String regex, String replacement)` 方法 该方法基于正则表达式来执行替换操作。它可以更灵活地处理复杂的匹配需求[^3]。 ```java public class ReplaceAllExample { public static void main(String[] args) { String text = "abc123def456ghi789"; String result = text.replaceAll("\\d+", "*"); // 将所有数字替换成 &#39;*&#39; System.out.println(result); // 输出: abc*def*ghi* } } ``` #### 3. 使用 `replaceFirst(String regex, String replacement)` 方法 与 `replaceAll()` 不同的是,这个方法仅替换第一个匹配到的内容[^4]。 ```java public class ReplaceFirstExample { public static void main(String[] args) { String sentence = "The cat and the dog."; String modifiedSentence = sentence.replaceFirst("the", "a"); System.out.println(modifiedSentence); // 输出: The cat and a dog. } } ``` #### 4. 去除首尾空白字符——使用 `trim()` 方法 虽然严格来说这不是一种替换方法,但它可以用来移除字符串两端多余的空格或其他不可见字符[^5]。 ```java public class TrimExample { public static void main(String[] args) { String messyText = " Hello Universe! "; String cleanText = messyText.trim(); System.out.println(cleanText); // 输出: Hello Universe! } } ``` 以上就是一些常用的 Java 字符串替换技术。每种都有其特定的应用场景,请根据实际需要选择合适的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值