从字符串中提取重复的字符

huangapple go评论67阅读模式
英文:

extract duplicate characters from a string

问题

我有一个家庭作业任务,我需要从一个字符串中提取重复的字符并将它们放入另一个字符串中。
例如:

const str = "love to learn javascript";

新的字符串将是:

const str2 = "love tarnjscip";

我还没有尝试过,因为我是初学者,不知道从哪里开始(我认为解决方案可能涉及嵌套循环)。

您能帮助我并提供不同的处理这种练习的方法吗?

英文:

I have a homework assignment where I have to extract duplicate characters from a string and place them in another string.
exp:

const str = "love to learn javascript"

the new string would be

const str2 = "love tarnjscip"

I didn't made any try as I'm a beginner and I don't have an initial idea how to start (I think the solution is a nested loop)

Can you help me and give me different ways to handle this kind of exercise?

答案1

得分: 1

你可以使用 Set 来获得你想要的结果:

const r = [...new Set("love to learn javascript")].join('');
console.log(r);

关于 "提取重复值" 这个短语,Set 也可以很有用:

// 如果字符已注册且不是空格,
// 如果尚未添加,则将其添加到重复项,否则将其注册

const dups = new Set, set = new Set;
[..."love to learn javascript"].forEach(char =>
  set.has(char) && char !== ' ' && !dups.has(char) && dups.add(char) || set.add(char)
);

console.log('重复字符:', ...[...dups].sort());
英文:

You could use Set to get your desired result provided:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const r = [...new Set(&quot;love to learn javascript&quot;)].join(&#39;&#39;);
console.log(r);

<!-- end snippet -->

Regarding the "extracting duplicate values" phrase, Set could be useful too:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// if char is registered and not a space, 
// add it to duplicates if not added yet otherwise register it

const dups = new Set, set = new Set;
[...&quot;love to learn javascript&quot;].forEach(char =&gt;
  set.has(char) &amp;&amp; char !== &#39; &#39; &amp;&amp; !dups.has(char) &amp;&amp; dups.add(char) || set.add(char)
);

console.log(&#39;duplicated chars:&#39;, ...[...dups].sort());

<!-- end snippet -->

答案2

得分: 0

在这里,我创建了一个空数组,然后将每个唯一的字母添加到数组中。然后,在下一轮中,我检查是否已经添加了一个字母,如果已经添加了,那么这个字母就是重复的,然后我使用 continue 来跳到下一轮,如果这个字母不重复,我就添加这个字母。
希望这对你有用。

const sentence = "love to learn javascript"

const letters = []
let result = ''
for(const item of sentence)
{
  const check = letters.find((i)=>i===item)
  if(check)continue;
  letters.push(item)
  result += item
}
console.log(result)
英文:

here i created an empty array and i pushed to it every unique letter, then in the next round i check if a letter already added so it means the letter repeated then i call continue to skip to the next round if the letter repeated or i add the letter if it is not.
hope this works for you.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const sentence = &quot;love to learn javascript&quot;

const letters = []
let result = &#39;&#39;
for(const item of sentence)
{
  const check = letters.find((i)=&gt;i===item)
  if(check)continue;
  letters.push(item)
  result += item
}
console.log(result)

<!-- end snippet -->

答案3

得分: 0

你可以使用一个对象来轻松跟踪你已经遇到的字母。

const str = "love to learn javascript";

let str2 = "";

let letters = {};

for(let i=0, l=str.length; i<l; ++i) {
  let letter = str[i];
  if(!letters[letter]) { // 如果对象还没有以当前字母命名的属性
                       // 那么将该字母添加到结果字符串中
    str2 += letter;
  }
  letters[letter] = 1; // 设置对象属性为当前字母
}

console.log(str2);
英文:

You can use an object to easily keep track of which letters you already encountered.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const str = &quot;love to learn javascript&quot;

let str2 = &quot;&quot;;

let letters = {};

for(let i=0, l=str.length; i&lt;l; ++i) {
  let letter = str[i];
  if(!letters[letter]) { // if the object does not have a property
                         // named after the current letter yet
    str2 += letter; // then add that letter to the result string
  }
  letters[letter] = 1; // set the object property for the current letter
}

console.log(str2)

<!-- end snippet -->

答案4

得分: 0

这段代码遍历字符串 str 中的每个字符。它通过比较字符的最后出现位置索引和第一次出现位置索引来检查当前字符是否是重复的。如果它们不相等,那么意味着该字符出现了多次。

const str = "love to learn javascript";
let str2 = "";

for (let i = 0; i < str.length; i++) {
  if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
    if (!str2.includes(str[i])) {
      str2 += str[i];
    }
  }
}

console.log(str2);

演示

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->
const str = "love to learn javascript";
let str2 = "";

for (let i = 0; i < str.length; i++) {
  if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
    if (!str2.includes(str[i])) {
      str2 += str[i];
    }
  }
}

console.log(str2);

<!-- end snippet -->

希望这对你有所帮助。

英文:

This code iterates through each character in the str string. It checks if the current character is a duplicate by comparing the last occurrence index with the first occurrence index of that character. If they are not equal, it means the character appears more than once.

const str = &quot;love to learn javascript&quot;;
let str2 = &quot;&quot;;

for (let i = 0; i &lt; str.length; i++) {
  if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
    if (!str2.includes(str[i])) {
      str2 += str[i];
    }
  }
}

Demo

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

const str = &quot;love to learn javascript&quot;;
let str2 = &quot;&quot;;

for (let i = 0; i &lt; str.length; i++) {
  if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
    if (!str2.includes(str[i])) {
      str2 += str[i];
    }
  }
}

console.log(str2);

<!-- end snippet -->

答案5

得分: 0

这是来自JavaScript MDN文档的内容。

Set对象是值的集合。

集合中的值只能出现一次,它在集合中是唯一的。
平均而言,它比Array.prototype.includes更快。

因此,用于查找重复字符非常方便。

let str = 'love to learn javascript';
const remDup = [...new Set(str)].sort().join("");
console.log(remDup);
英文:

This is from the documentation of Javascript MDN.

Set -Javascript | MDN

Set objects are collections of values.

A value in the set may only occur once. it is unique in the set's collection.
It is, on average, faster than the Array.prototype.includes

Therefore, for finding duplicate characters comes very handy.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let str = &#39;love to learn javascript&#39;;
const remDup= [...new Set(str)].sort().join(&quot;&quot;);


console.log(remDup);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月13日 17:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定