呕心沥血算法题——串的处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26924703/article/details/81387572
// 串的处理
// 在实际的开发工作中,对字符串的处理是最常见的编程任务。
// 本题目即是要求程序对用户输入的串进行处理。具体规则如下:
// 1. 把每个单词的首字母变为大写。
// 2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
// 3. 把单词中间有多个空格的调整为1个空格。
// 例如:
// 用户输入:
// you and me what cpp2005program
// 则程序输出:
// You And Me What Cpp_2005_program
// 用户输入:
// this is a 99cat
// 则程序输出:
// This Is A 99_cat
// 我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。
// 每个单词间由1个或多个空格分隔。
// 假设用户输入的串长度不超过200个字符。

function makeString(str) {
   console.time("makeString");
   // 匹配单词(包括数字与字母的组合)
   var strs = str.match(/[a-z,A-Z,0-9]+/ig);
   let result = '';
   for (let i = 0; i < strs.length; i++) {
      let temp = strs[i];
      // 首字母大写
      temp = temp.replace(strs[i].charAt(0), strs[i].charAt(0).toUpperCase());
      // 添加'_'
      temp = temp.replace(/([A-z])([0-9])/, "$1_$2");
      temp = temp.replace(/([0-9])([A-z])/, "$1_$2");
      result += temp + ' ';
   }
   console.timeEnd("makeString");
   return result.trim();
}

let str = 'you and me what cpp2005program';
console.log(makeString(str));

猜你喜欢

转载自blog.csdn.net/qq_26924703/article/details/81387572