题目描述请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
1、第一种解题方式
这种解题方式中用到了StringBuffer类中的两种方法,
第一种是indexOf(String str,int index)这种方法是实例化方法,作用是将字符串中的含有str的索引返回,返回值为int类型,第二个参数index的含义是从字符串的第index位去找。
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
第二种方法是lastIndexof()
public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1
2、加深理解了toString()方法:
这种方法不只是在传入字符串引用时返回字符串本身,更重要的功能是将其他类型转换成String类型,本代码中就使用了这种方法将StringBuffer()转换为String类型,从而可以使用contains()函数。
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;
}
}
}