博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
空格替换
阅读量:4680 次
发布时间:2019-06-09

本文共 1753 字,大约阅读时间需要 5 分钟。

  

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
此类题目,如果用java编写可以直接采用内置的替换函数
import java.util.Scanner;public class ReplaceSpace {	public String replaceSpace(StringBuffer str) {		String str2 = str.toString();		String strNew = str2.replace(" ", "%20");//替换字符		//String strNew = str2.replaceAll(" ", "%20");//正则表达式				return strNew; 	    }	public static void main(String[] args){		Scanner in = new Scanner(System.in);		String str = in.nextLine();		ReplaceSpace a = new ReplaceSpace();		System.out.println(a.replaceSpace(new StringBuffer(str)));	}}

  没有问题,如果参考替换的源码,对于字符的替换:

string.java内的源码是:

public String replace(char oldChar, char newChar) {        if (oldChar != newChar) {            int len = value.length;            int i = -1;            char[] val = value; /* avoid getfield opcode */            while (++i < len) {                if (val[i] == oldChar) {                    break;                }            }            if (i < len) {                char buf[] = new char[len];                for (int j = 0; j < i; j++) {                    buf[j] = val[j];                }                while (i < len) {                    char c = val[i];                    buf[i] = (c == oldChar) ? newChar : c;                    i++;                }                return new String(buf, true);            }        }        return this;    }
View Code

遍历一遍,直接替换,对于字符的替换,repalce函数是采用的字符匹配实现的。

我们可以采用此思路进行字符串替换。

首先要将字符串分割到String数组中去,然后直接遍历替换即可,整个过程遍历1遍,时间复杂度为O(n)

代码:

import java.util.Scanner;public class ReplaceSpace2 {	public String replaceSpace(StringBuffer str) {		String[] strArr = str.toString().split("");		str = new StringBuffer();		for(int i=0; i

  

 

转载于:https://www.cnblogs.com/feichangnice/p/7662192.html

你可能感兴趣的文章