08:字符串替换空格

爱被打了一巴掌 2023-02-22 10:43 29阅读 0赞

题目:替换空格

实现一个函数,存在字符串hello world!!!,将字符串内的空格字符替换为’%20’。
先对空格个数进行计数,得到适当大小的字符数组,接着将原本数组从后向前替换到新数组中。

  1. public class Offer08 {
  2. public static void main(String[] args) {
  3. String string = "hello world! !";
  4. System.out.println(replaceBlank(string));
  5. }
  6. public static String replaceBlank(String str){
  7. if(str==null||str.length()==0)return null;
  8. char[] chars = str.toCharArray();
  9. //空格计数
  10. int count=0;
  11. for (char c : chars) {
  12. if(c==' ')count++;
  13. }
  14. //新数组大小
  15. int ti = count*2+chars.length;
  16. char[] temp = new char[ti];
  17. //下标
  18. ti--;
  19. //替换
  20. for (int i=chars.length-1;i>=0;i--){
  21. if(chars[i]==' '){
  22. temp[ti--] = '0';
  23. temp[ti--] = '2';
  24. temp[ti--] = '%';
  25. }else{
  26. temp[ti--] = chars[i];
  27. }
  28. }
  29. return new String(temp);
  30. }
  31. }

发表评论

表情:
评论列表 (有 0 条评论,29人围观)

还没有评论,来说两句吧...

相关阅读