zoukankan      html  css  js  c++  java
  • 剑指offer(Java版)第三题:请实现一个函数,把字符串中的每个空格替换成"%20"。 例如输入“We are happy.”,则输出“We%20are%20happy.”。

    /*
    请实现一个函数,把字符串中的每个空格替换成"%20"。
    例如输入“We are happy.”,则输出“We%20are%20happy.”。
    */

    import java.util.*;
    import java.lang.*;

    public class Class4 {

    static class replaceBlank{
    public String replaceBlank(StringBuffer a){
    if(a == null){
    System.out.println("输入的字符串为空!");
    return null;
    }
    int newLength = a.length();
    int originLength = a.length() - 1;
    int count = 0;
    for(int i = 0; i < a.length(); i++){
    if(a.charAt(i) == ' '){
    count++;
    newLength += 2;
    }
    }
    a.setLength(newLength);
    if(count == 0){
    System.out.println("输入的字符串不包括空格!");
    return "Worry";
    }
    newLength = newLength - 1;
    while(newLength > originLength){
    if(a.charAt(originLength) != ' '){
    a.setCharAt(newLength--, a.charAt(originLength));
    }else if(a.charAt(originLength) == ' '){
    a.setCharAt(newLength--, '0');
    a.setCharAt(newLength--, '2');
    a.setCharAt(newLength--, '%');
    }
    originLength--;
    }
    return a.toString();
    }
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("输入原始字符串!");
    StringBuffer s1 = new StringBuffer("We are happy");
    System.out.println(s1.toString());
    replaceBlank rb = new replaceBlank();
    String r = rb.replaceBlank(s1);
    System.out.println("输出替换后的字符串!");
    System.out.println(r);

    }

    }

  • 相关阅读:
    汉诺塔难题
    函数的两种调用方式

    汉诺塔难题
    汉诺塔难题

    python中对小数取整
    linux中部署apache服务(http服务或者web服务)
    python中如何判断变量类型
    python中求余数
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12371703.html
Copyright © 2011-2022 走看看