$array = array('a', 'b', 'c', 'd', /*... letters from 3 alphabets*/);
$letter = 'some symbol, posted by user'; // real length = 1
How to get know, is $letter
one of the symbols, listed in $array
?
Like, if $letter = 'G'
and there is no G
in $array
, well then return false
.
Yep, I tried in_array()
, but there are too many symbols, is there any other (shorter) solution?
ref:
In javascript, how do you search an array for a substring match
The solution given here is generic unlike the solution 4556343#4556343, which requires a previous parse to identify a string with which to join()
, that is not a component of any of the array strings.
Also, in that code /!id-[^!]*/
is more correctly, /![^!]*id-[^!]*/
to suit the question parameters:
- «search an array …» (of strings or numbers and not functions, arrays, objects, etc.)
- «for only part of the string to match » (match can be anywhere)
- «return the … matched … element» (singular, not ALL, as in «… the … elementS»)
- «with the full string» (include the quotes)
… NetScape / FireFox solutions (see below for a JSON
solution):
javascript: /* "one-liner" statement solution */
alert(
["x'!x'"id-2",'' "id-1 "', "item","thing","id-3-text","class" ] .
toSource() . match( new RegExp(
'[^\\]("([^"]|\\")*' + 'id-' + '([^"]|\\")*[^\\]")' ) ) [1]
);
or
javascript:
ID = 'id-' ;
QS = '([^"]|\\")*' ; /* only strings with escaped double quotes */
RE = '[^\\]("' +QS+ ID +QS+ '[^\\]")' ;/* escaper of escaper of escaper */
RE = new RegExp( RE ) ;
RA = ["x'!x'"id-2",'' "id-1 "', "item","thing","id-3-text","class" ] ;
alert(RA.toSource().match(RE)[1]) ;
displays "x'!x'"id-2"
.
Perhaps raiding the array to find ALL matches is ‘cleaner’.
/* literally (? backslash star escape quotes it!) not true, it has this one v */
javascript: /* purely functional - it has no ... =! */
RA = ["x'!x'"id-2",'' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
ra.unshift(void 0) ; /* cheat the [" */
return ra . toSource() . match( new RegExp(
'[^\\]"' + '([^"]|\\")*' + id + '([^"]|\\")*' + '[^\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('nn') ) ;
displays:
"x'!x'"id-2" "' "id-1 "" "id-3-text"
Using, JSON.stringify()
:
javascript: /* needs prefix cleaning */
RA = ["x'!x'"id-2",'' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
return JSON.stringify( ra ) . match( new RegExp(
'[^\\]"([^"]|\\")*' + id + '([^"]|\\")*[^\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('nn') ) ;
displays:
["x'!x'"id-2" ,"' "id-1 "" ,"id-3-text"
wrinkles:
- The «unescaped» global RegExp is
/[^]"([^"]|")*id-([^"]|")*[^]"/g
with theto be found literally. In order for
([^"]|")*
to match strings with all"
‘s escaped as"
, theitself must be escaped as
([^"]|\")*
. When this is referenced as a string to be concatenated withid-
, eachmust again be escaped, hence
([^"]|\\")*
! - A search
ID
that has a,
*
,"
, …, must also be escaped via.toSource()
orJSON
or … . null
search results should return''
(or""
as in an EMPTY string which contains NO"
!) or[]
(for all search).- If the search results are to be incorporated into the program code for further processing, then
eval()
is necessary, likeeval('['+findInRA(RA,ID).join(',')+']')
.
———————————————————————————
Digression:
Raids and escapes? Is this code conflicted?
The semiotics, syntax and semantics of /* it has no ... =! */
emphatically elucidates the escaping of quoted literals conflict.
Does «no =» mean:
- «no ‘=’ sign» as in
javascript:alert('x3D')
(Not! Run it and see that there is!), - «no javascript statement with the assignment operator»,
- «no equal» as in «nothing identical in any other code» (previous code solutions demonstrate there are functional equivalents),
- …
Quoting on another level can also be done with the immediate mode javascript protocol URI’s below. (// commentaries end on a new line (aka nl, ctrl-J, LineFeed, ASCII decimal 10, octal 12, hex A) which requires quoting since inserting a nl, by pressing the Return key, invokes the URI.)
javascript:/* a comment */ alert('visible') ;
javascript:// a comment ; alert( 'not' ) this is all comment %0A;
javascript:// a comment %0A alert('visible but %A is wrong ') // X %0A
javascript:// a comment %0A alert('visible but %'+'0A is a pain to type') ;
Note: Cut and paste any of the javascript:
lines as an immediate mode URI (at least, at most?, in FireFox) to use first javascript:
as a URI scheme or protocol and the rest as JS labels.
Может кто подсказать, как проверить что определённый символ содержится в массиве с символами?
Моя проблема сейчас в том что мой способ работает некорректно. Не могу понять как заставить искать конкретно первую букву во всём массиве потом вторую и так до конца.
#include <iostream>
using namespace std;
std::string letters[26] = ['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'];
string myString = "hello";
void Encode(){
letters.for(i = 0;i<letters.length;i++){
if(myString[i] == letters[i])
}
}
int main()
{
cout<<"Hello World";
return 0;
}
#arrays #c #duplicates
Вопрос:
Я создаю программу, которая требует от пользователя ввода аргумента (argv[1]), где аргументом является каждая буква алфавита, переставленная так, как это нравится пользователю. Примерами допустимых входных данных являются «YTNSHKVEFXRBAUQZCLWDMIPGJO» и «JTREKYAVOGDXPSNCUIZLFBMWHQ». Примерами недопустимого ввода будут «VCHPRZGJVTLSKFBDQWAXEUYMOI» и «ABCDEFGHIJKLMNOPQRSTUYYYY», поскольку в соответствующих примерах есть дубликаты » V » и «Y».
Что я знаю до сих пор, так это то, что вы можете просмотреть весь аргумент следующим образом
for (int j = 0, n = strlen(argv[1]); j < n; j )
{
//Place something in here...
}
Однако я не совсем знаю, будет ли это правильным путем при поиске дубликатов? Кроме того, я хочу, чтобы ответ был как можно более простым, я знаю, что время и загрузка процессора не являются приоритетом, поэтому «лучший» алгоритм не обязательно тот, который я ищу.
Комментарии:
1. В конечном итоге вам потребуется проверить каждый отдельный символ ввода, поэтому для начала неплохо было бы просмотреть их все.
2. Как бы вы это сделали, если бы вам вручили листок бумаги с указанной последовательностью символов, и все, что у вас было, — это еще один лист бумаги и карандаш? Ответьте на это, и у вас будет один (из нескольких) возможных алгоритмов.
3. Самый простой вариант, на мой взгляд, — это вариант использования switch(arg[i]) { регистр ‘A’: int x ; перерыв; и так далее в алфавитном порядке.
4. n = strlen(argv[1] не работает. n=0.
Ответ №1:
предполагая, что все ваши буквы написаны заглавными буквами, вы можете использовать хэш-таблицу, чтобы заставить этот алгоритм работать O(n)
со сложностью во времени.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j )
{
arr[argv[1][j]-'A'] ;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A' 1;i ){
if(arr[i]>=2)printf("%c ",i 'A');
}
}
здесь мы создаем массив arr
, инициализированный нулями. этот массив будет вести учет вхождений каждой буквы.
а затем мы ищем буквы, которые появлялись 2 или более раз, это дублированные буквы.
Также, используя тот же массив, вы можете проверить, все ли буквы встречались хотя бы один раз, чтобы проверить, является ли это перестановкой
Ответ №2:
Попробовать это.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
size_t ascii[256] = {0, };
char * cursor = input;
char c = '';
while((c=*cursor ))
{
if(ascii[c] == 0)
ascii[c];
else
{
printf("Find %c has existed.n", c);
break;
}
}
return 0;
}
Ответ №3:
Я не знаю, тот ли это тип кода, который вы ищете, но вот что я сделал. Он ищет дубликаты в данном наборе строк.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i ){
for(int j=i 1; j<length; j ){
if(stringArg[i] == stringArg[j]){
dupliCount =1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
В этом посте будет обсуждаться, как проверить наличие заданного элемента в массиве в C#. Решение должно возвращать true, если массив содержит указанное значение; в противном случае ложно.
1. Использование Enumerable.Contains()
метод (System.Linq
)
The Enumerable.Contains() предоставляет простой и понятный способ определить, содержит ли последовательность указанный элемент или нет. Следующий пример демонстрирует использование Contains()
метод:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Linq; public static class Extensions { public static bool find<T>(this T[] array, T target) { return array.Contains(target); } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
2. Использование Array.Exists()
метод
The Array.Exists() рекомендуемым решением является проверка существования элемента в массиве. В следующем примере кода показано, как это реализовать.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public static class Extensions { public static bool find<T>(this T[] array, T target) { return Array.Exists(array, x => x.Equals(target)); } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
3. Использование Array.IndexOf()
метод
Другим хорошим решением является использование Array.IndexOf() метод, который возвращает индекс первого вхождения указанного элемента в этот массив и -1
если такого элемента нет.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public static class Extensions { public static bool find<T>(this T[] array, T target) { return Array.IndexOf(array, target) != —1; } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
4. Использование Array.FindIndex()
метод
Array.FindIndex() возвращает индекс первого элемента, удовлетворяющего предоставленному предикату. Если ни один элемент не удовлетворяет условию, FindIndex
возвращается -1
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public static class Extensions { public static bool find<T>(this T[] array, T target) { return Array.FindIndex(array, x => x.Equals(target)) != —1; } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
5. Использование HashSet
HashSet
класс обеспечивает Contains
метод, чтобы определить, содержит ли заданный объект указанный элемент. В следующем примере данный массив преобразуется в набор и вызывается его Contains
метод:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Collections.Generic; public static class Extensions { public static bool find<T>(this T[] array, T target) { return new HashSet<T>(array).Contains(target); } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
6. Использование Enumerable.Where()
метод (System.Linq
)
The System.Linq.Enumerable.Where() Метод фильтрует последовательность значений на основе предиката. В следующем примере кода показано, как мы можем использовать Where()
чтобы найти первое вхождение указанного элемента в этом массиве.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; using System.Linq; public static class Extensions { public static bool find<T>(this T[] array, T target) { try { array.Where(i => i.Equals(target)).First(); // или же // array.First(i => i.Equals(target)); return true; } catch (InvalidOperationException) { return false; } } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
Мы можем избежать блока try-catch, установив значение по умолчанию с помощью DefaultIfEmpty()
метод:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Linq; public static class Extensions { public static bool find(this int[] array, int target) { return (array.Where(i => i.Equals(target)) .DefaultIfEmpty(—1) .First()) != —1; } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
7. Использование Array.FindAll()
метод
Array.FindAll() Метод возвращает массив, содержащий все элементы, соответствующие указанному предикату. Мы можем использовать его следующим образом, чтобы проверить наличие элемента в массиве.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; public static class Extensions { public static bool find<T>(this T[] array, T target) { T[] results = Array.FindAll(array, x => x.Equals(target)); return results.Length > 0; } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
8. Выполнение линейного поиска
Наивное решение состоит в том, чтобы выполнить линейный поиск в заданном массиве, чтобы определить, присутствует ли целевой элемент в массиве.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System; using System.Collections.Generic; public static class Extensions { public static bool find<T>(this T[] array, T target) { EqualityComparer<T> comparer = EqualityComparer<T>.Default; for (int i = 0; i < array.Length; i++) { if (comparer.Equals(array[i], target)) { return true; } } return false; } } public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int target = 4; bool isExist = array.find(target); if (isExist) { Console.WriteLine(«Element found in the array»); } else { Console.WriteLine(«Element not found in the given array»); } } } /* результат: Element found in the array */ |
Скачать Выполнить код
Это все о поиске элемента в массиве в C#.