0
点赞
收藏
分享

微信扫一扫

【打卡】删除字符串中指定位置的内容

数数扁桃 2022-04-25 阅读 191
leetcodejava

描述
请编写代码,使用 StringBuffer 类中的相关方法来删除字符串中指定位置的内容。

在本题的 Solution 类中有个 deleteString 方法,该方法有一个 String 类型的参数 str 和两个 int 类型的参数 indexStart, indexEnding。str 代表原始字符串,indexStart 代表需要删除内容的开始位置,indexEnding 代表需要删除内容的结束位置。该方法要删除原始字符串中指定位置的内容,并返回删除指定内容之后的字符串,返回值为 StringBuffer 类型。

样例
样例一

如果输入的数据为 abc 1 2 则返回:

ac

样例二

如果输入的数据为 abcde 1 4 则返回:

ae

解法一:StringBuffer 类中 delete() 方法

public class Solution {
    /**
     * @param str   str represents the string passed in
     * @param indexStart    indexStart represents the start position of the
     *                  content to be deleted
     * @param indexEnding    indexEnding represents the end position of the
     *                  content to be deleted
     * @return  return means to return the string after deleting the specified
     *          position
     */
    public StringBuffer deleteString(String str, int indexStart, 
        int indexEnding) {
        // write your code here
        // 使用 StringBuffer 的构造方法,将 String 类型转为 StringBuffer 类型 
        StringBuffer stringBuffer = new StringBuffer(str);
        // 调用StringBuffer 中的 delete(int start, int end) 方法, 
        // 删除时包含 start 索引,不包含 end 索引 
        stringBuffer.delete(indexStart, indexEnding);
        return stringBuffer;
        
    }
}

解法二:StringBuilder 类中 delete() 方法

public class Solution { 
    public StringBuffer deleteString(String str, int indexStart, int indexEnding) { 
        // 使用 StringBuilder 的构造方法,将 String 类型转为 StringBuilder 类型 
        StringBuilder stringBuilder = new StringBuilder(str); 
        // 调用 StringBuilder 中的 delete(int start, int end) 方法, 
        // 删除时包含 start 索引,不包含 end 索引 
        String str = stringBuilder.delete(indexStart, indexEnding).toString(); 
        StringBuffer stringBuffer = new StringBuffer(str); 
        return stringBuffer; 
    } 
}
举报

相关推荐

0 条评论