題目描述請實現(xiàn)一個函數(shù),將一個字符串中的每個空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
1、第一種解題方式
? ? ? ? 這種解題方式中用到了StringBuffer類中的兩種方法,
? ? ? 第一種是indexOf(String str,int index)這種方法是實例化方法,作用是將字符串中的含有str的索引返回,返回值為int類型,第二個參數(shù)index的含義是從字符串的第index位去找。
public int indexOf(int ch):?返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int indexOf(int ch, int fromIndex):?返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
int indexOf(String str):?返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
int indexOf(String str, int fromIndex):?返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
? ? ? ? 第二種方法是lastIndexof()
public int lastIndexOf(int ch):?返回指定字符在此字符串中最后一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(int ch, int fromIndex):?返回指定字符在此字符串中最后一次出現(xiàn)處的索引,從指定的索引處開始進行反向搜索,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(String str):?返回指定子字符串在此字符串中最右邊出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(String str, int fromIndex):?返回指定子字符串在此字符串中最后一次出現(xiàn)處的索引,從指定的索引開始反向搜索,如果此字符串中沒有這樣的字符,則返回 -1
2、加深理解了toString()方法:
這種方法不只是在傳入字符串引用時返回字符串本身,更重要的功能是將其他類型轉換成String類型,本代碼中就使用了這種方法將StringBuffer()轉換為String類型,從而可以使用contains()函數(shù)。
public class Solution
{
? ? public static String replaceSpace(StringBuffer str)
? ? {
? ? ? ? String result=str.toString();
? ? ? ? if(result.contains(" "))
? ? ? ? {
? ? ? ? ? ? while(str.indexOf(" ")!=str.lastIndexOf(" "))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? int index=str.indexOf(" ");
? ? ? ? ? ? ? ? str.replace(index,index+1,"%20");
? ? ? ? ? ? }
? ? ? ? ? ? int index=str.indexOf(" ");
? ? ? ? ? ? str.replace(index,index+1,"%20");
? ? ? ? ? ? result =str.toString();
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? return result;
? ? ? ? }
? ? }
}