简体   繁体   English

如何从字符串中获取奇数和偶数位置字符?

[英]How to get odd and even position characters from a string?

I'm trying to figure out how to remove every second character (starting from the first one) from a string in Javascript. 我试图弄清楚如何从Javascript中的字符串中删除第二个字符(从第一个字符开始)。 For example, the string "This is a test!" 例如,字符串“这是一个测试!” should become "hsi etTi sats!" 应该成为“ hsi etTi sats”! I also want to save every deleted character into another array. 我也想将每个删除的字符保存到另一个数组中。

I have tried using replace method and splice method, but wasn't able to get them to work properly. 我尝试使用replace方法和splice方法,但是无法使其正常工作。 Mostly because replace only replaces the first character. 主要是因为replace只替换第一个字符。

function encrypt(text, n) {
  if (text === "NULL") return n;
  if (n <= 0) return text;
  var encArr = [];
  var newString = text.split("");
  var j = 0;
  for (var i = 0; i < text.length; i += 2) {
    encArr[j++] = text[i];
    newString.splice(i, 1); // this line doesn't work properly
  }
}

You could reduce the characters of the string and group them to separate arrays using the % operator. 您可以reduce字符串的字符,并使用%运算符将它们分组为单独的数组。 Use destructuring to get the 2D array returned to separate variables 使用解构使二维数组返回到单独的变量

 let str = "This is a test!"; const [even, odd] = [...str].reduce((r,char,i) => (r[i%2].push(char), r), [[],[]]) console.log(odd.join('')) console.log(even.join('')) 

Using a for loop: 使用for循环:

 let str = "This is a test!", odd = [], even = []; for (var i = 0; i < str.length; i++) { i % 2 === 0 ? even.push(str[i]) : odd.push(str[i]) } console.log(odd.join('')) console.log(even.join('')) 

It would probably be easier to use a regular expression and .replace : capture two characters in separate capturing groups, add the first character to a string, and replace with the second character. 使用正则表达式和.replace可能会更容易:在单独的捕获组中捕获两个字符,将第一个字符添加到字符串中,然后替换为第二个字符。 Then, you'll have first half of the output you need in one string, and the second in another: just concatenate them together and return: 然后,将需要的输出的前一半放在一个字符串中,将第二个字符串放在另一个字符串中:将它们连接在一起并返回:

 function encrypt(text) { let removedText = ''; const replacedText1 = text.replace(/(.)(.)?/g, (_, firstChar, secondChar) => { // in case the match was at the end of the string, // and the string has an odd number of characters: if (!secondChar) secondChar = ''; // remove the firstChar from the string, while adding it to removedText: removedText += firstChar; return secondChar; }); return replacedText1 + removedText; } console.log(encrypt('This is a test!')); 

You could take an array and splice and push each second item to the end of the array. 您可以采用一个数组并进行拼接,然后将每个第二项推到数组的末尾。

 function encrypt(string) { var array = [...string], i = 0, l = array.length >> 1; while (i <= l) array.push(array.splice(i++, 1)[0]); return array.join(''); } console.log(encrypt("This is a test!")); 

 function encrypt(text) { text = text.split(""); var removed = [] var encrypted = text.filter((letter, index) => { if(index % 2 == 0){ removed.push(letter) return false; } return true }).join("") return { full: encrypted + removed.join(""), encrypted: encrypted, removed: removed } } console.log(encrypt("This is a test!")) 

Splice does not work, because if you remove an element from an array in for loop indexes most probably will be wrong when removing another element. 拼接不起作用,因为如果在for loop索引中从数组中删除一个元素,则在删除另一个元素时很可能会出错。

Pretty simple with .reduce() to create the two arrays you seem to want. 使用.reduce()简单,可以创建您想要的两个数组。

 function encrypt(text) { return text.split("") .reduce(({odd, even}, c, i) => i % 2 ? {odd: [...odd, c], even} : {odd, even: [...even, c]} , {odd: [], even: []}) } console.log(encrypt("This is a test!")); 

They can be converted to strings by using .join("") if you desire. 如果需要,可以使用.join("")将它们转换为字符串。

I think you were on the right track. 我认为您在正确的轨道上。 What you missed is replace is using either a string or RegExp. 您错过的替换是使用字符串或RegExp。

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. replace()方法返回一个新字符串,该字符串具有部分或全部模式匹配项,并由替换项替换。 The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. 模式可以是字符串或RegExp,而替换项可以是字符串或每个匹配项要调用的函数。 If pattern is a string, only the first occurrence will be replaced. 如果pattern是字符串,则只会替换第一个匹配项。

Source: String.prototype.replace() 资料来源: String.prototype.replace()

If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. 如果要替换值(而不是正则表达式),则仅替换该值的第一个实例。 To replace all occurrences of a specified value, use the global (g) modifier 要替换所有出现的指定值,请使用全局(g)修饰符

Source: JavaScript String replace() Method 来源: JavaScript String replace()方法

So my suggestion would be to continue still with replace and pass the right RegExp to the function, I guess you can figure out from this example - this removes every second occurrence for char 't': 因此,我的建议是继续使用replace并将正确的RegExp传递给该函数,我想您可以从此示例中弄清楚-这样就消除了char't'的第二次出现:

 let count = 0; let testString = 'test test test test'; console.log('original', testString); // global modifier in RegExp let result = testString.replace(/t/g, function (match) { count++; return (count % 2 === 0) ? '' : match; }); console.log('removed', result); 

like this? 像这样?

 var text = "This is a test!" var result = "" var rest = "" for(var i = 0; i < text.length; i++){ if( (i%2) != 0 ){ result += text[i] } else{ rest += text[i] } } console.log(result+rest) 

Maybe with split, filter and join: 也许使用split,filter和join:

const remaining = myString.split('').filter((char, i) => i % 2 !== 0).join('');
const deleted = myString.split('').filter((char, i) => i % 2 === 0).join('');

I don't know how much you care about performance, but using regex is not very efficient. 我不知道您对性能有多重视,但是使用正则表达式不是很有效。 Simple test for quite a long string shows that using filter function is on average about 3 times faster, which can make quite a difference when performed on very long strings or on many, many shorts ones. 对相当长的字符串进行的简单测试表明,使用过滤器功能的速度平均快了约3倍,这在处理非常长的字符串或许多很多短裤的字符串时会产生很大的不同。

 function test(func, n){ var text = ""; for(var i = 0; i < n; ++i){ text += "a"; } var start = new Date().getTime(); func(text); var end = new Date().getTime(); var time = (end-start) / 1000.0; console.log(func.name, " took ", time, " seconds") return time; } function encryptREGEX(text) { let removedText = ''; const replacedText1 = text.replace(/(.)(.)?/g, (_, firstChar, secondChar) => { // in case the match was at the end of the string, // and the string has an odd number of characters: if (!secondChar) secondChar = ''; // remove the firstChar from the string, while adding it to removedText: removedText += firstChar; return secondChar; }); return replacedText1 + removedText; } function encrypt(text) { text = text.split(""); var removed = ""; var encrypted = text.filter((letter, index) => { if(index % 2 == 0){ removed += letter; return false; } return true }).join("") return encrypted + removed } var timeREGEX = test(encryptREGEX, 10000000); var timeFilter = test(encrypt, 10000000); console.log("Using filter is faster ", timeREGEX/timeFilter, " times") 

过滤器与正则表达式-性能测试结果

Using actually an array for storing removed letters and then joining them is much more efficient, than using a string and concatenating letters to it. 实际上,使用数组存储删除的字母然后将它们连接起来比使用字符串并将字母串联在一起要有效得多。
I changed an array to string in filter solution to make it the same like in regex solution, so they are more comparable. 我在过滤器解决方案中将数组更改为字符串,以使其与正则表达式解决方案相同,因此它们的可比性更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在每个奇数和偶数位置分块字符串 - Chunk a string every odd and even position 如何从奇数数组中获取字符串? - How to get string from odd's array ? 如何从Ramda的数组中获取偶数和奇数条目 - How to get the even and odd entries from an array with Ramda 如何以最简单的方式从数组中获取单个偶数或奇数? - How to get single even or odd number from a array in simplest way? 如何在一行中将字符串偶数索引和奇数索引字符打印为 2 个空格分隔的字符串? - How to print string even-indexed and odd-indexed characters as 2 space-separated strings on a single line? 将字符串中的奇数和偶数索引字符转换为 Javascript 中的大写/小写? - Converting Odd and Even-indexed characters in a string to uppercase/lowercase in Javascript? 如何根据字符串中的单词数组获取单词字符在字符串中的位置 - How to get position of a word characters in a string based on an array of words in this string 如果数组的元素处于奇数或偶数位置,我如何在 Javascript 中查看? - How can I see in Javascript if the element of an array is in an odd or in an even position? 如何使用Javascript从数组中获取奇/偶值并在表中显示 - How to get odd/even value from array and display in table using Javascript 从数组 JavaScript 中查找特定字符串是奇数还是偶数 - Finding specific string is odd or even from an array JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM