如何检查字符串是否包含另一个字符串的元素 [英] How do I check if a string has the elements of the other string

查看:254
本文介绍了如何检查字符串是否包含另一个字符串的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会在这里弄乱代码,但我正在努力解决包括。

所以这个版本只检查句子的长度而不是元素...我可以输入字母a的第26条并接受它...我想测试输入是否至少有一个字母表的elemenet至少一次。

PS:我是编程新手。



我的尝试:



I might be messing up here the code, but I'm trying to work around include.
So this version checks only for the length of the sentence but not the elements... I can type 26 of letter a and will accept it... I want to test if the input has each elemenet of alphabet at least once.
PS: I'm new to programming.

What I have tried:

var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var input = prompt("Type in a message","");
	for ( i = 0; i < alphabet.length; i++) {
	if(input.includes(alphabet[i])) {
		alert("Bingo");
	} else { 
		alert("Bollocks!");
}
}

推荐答案

'快速的棕色狐狸跳过懒狗'

算法:

你知道当你找到一个不在句子中的1个字母时,所有字母都不在句子中。

你知道所有字母都是当你在句子里找到每个字母的句子。



翻译:

'The quick brown fox jumps over the lazy dog'
Algorithm:
You know that all letters are not in a sentence when you have found 1 letter that is not in the sentence.
You know that all letters are in a sentence when you have found each letter in the sentence.

Translation:
set an answer variable to true
Check each letter in a loop
    if the letter is not in sentence
        answer is false
then after loop, check if answer is true or false and do what you want.
if answer is true
    bingo
else
    Bollocks


var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var input = prompt("Type in a message","");
var i;
for ( i = 0; i < alphabet.length; i++) 
{
  if(input.includes(alphabet[i]) == false) 
    break;
} 
if ( i == alphabet.length)
  alert("Bingo");
else 
  alert("Bollocks!"); 


试试这个,



Try this,

var occurencePositive = 0;
for(var index = 0; index <alphabet.lenght; index++){
    if(input.IndexOf(alphabet[index]) > -1){
       //increase counter when match is found in string.
       occurencePositive++;
    }
}

if(occurencePositive == alphabet.length - 1){
  alert("Bingo");
} 
else { 
  alert("Bollocks!");
}





希望这会有所帮助。



Hope this helps.


这篇关于如何检查字符串是否包含另一个字符串的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆