zoukankan      html  css  js  c++  java
  • JavaScript里面的居民们3-去除空格和重复

    如代码,分别实现 diyTrim 及 removeRepetition 函数,并跑通代码中的测试用例。

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <meta charset="utf-8" />
     5     <title>JS里的居民们3</title>
     6 
     7 </head>
     8 <body>
     9     <script>
    10     /*
    11 实现一个字符串头尾去除空格的函数
    12 注意需要去除的空格,包括全角、半角空格
    13 暂时不需要学习和使用正则表达式的方式
    14 */
    15 function diyTrim(str) {
    16 //遍历一下每个字符前后是否为空格,是的话进行切割字符串,直到没有空格,结束循环。
    17 for(i=0;i<str.length;i++){
    18     if(str[0]==" "||str[0]==" "){
    19         str=str.slice(1);
    20     }
    21     else if(str[str.length-1]==" "||str[str.length-1]==" "){
    22         str=str.slice(0,str.length-2);
    23     }
    24     else{
    25         break;
    26     }
    27 }
    28     return str;
    29 }
    30 
    31 // 测试用例
    32 console.log(diyTrim(' a f b    ')); // ->a f b
    33 console.log(diyTrim('    ffdaf    ')); // ->ffdaf
    34 console.log(diyTrim('1    ')); // ->1
    35 console.log(diyTrim('  f')); // ->f
    36 console.log(diyTrim('     a f b    ')); // ->a f b
    37 console.log(diyTrim(' ')); // ->
    38 console.log(diyTrim(' ')); // ->
    39 console.log(diyTrim('')); // ->
    40 
    41 /*
    42 去掉字符串str中,连续重复的地方
    43 */
    44 function removeRepetition(str) {
    45     var result = "";
    46 
    47     for(i=0,len=str.length;i<len;i++){//定义len,每次循环都会改变长度
    48         if(str[0]==str[1]){//判断前后是否一致
    49             str=str.slice(1);//记得赋值给str,不然就是原来的数组。
    50         }
    51         else{
    52             result=result+str[0];//存入不重复的值,并且要往后继续移一个
    53             str=str.slice(1);
    54         }
    55     }
    56     return result;
    57 }
    58 
    59 // 测试用例
    60 console.log(removeRepetition("aaa")); // ->a
    61 console.log(removeRepetition("abbba")); // ->aba
    62 console.log(removeRepetition("aabbaabb")); // ->abab
    63 console.log(removeRepetition("")); // ->
    64 console.log(removeRepetition("abc")); // ->abc
    65 </script>
    66 </body>
    67 </html>
  • 相关阅读:
    数据结构-堆(优先队列)习题
    数据结构-二叉搜索树习题
    数据结构-树习题
    数据结构-队列习题
    数据结构-堆栈习题
    数据结构-链表习题
    数据结构-顺序表习题
    数据结构-概论习题
    C语言中的stdin,stdout,stderr[转]
    SQL Server 查询数据库表结构
  • 原文地址:https://www.cnblogs.com/Joe-and-Joan/p/10072340.html
Copyright © 2011-2022 走看看