I need to search a string in the string array. I dont want to use any for looping in it
string [] arr = {"One","Two","Three"};
string theString = "One"
I need to check whether theString variable is present in arr.
Neo
3,3097 gold badges34 silver badges44 bronze badges
asked Nov 5, 2008 at 12:12
0
Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn’t fully implemented)… so if you just don’t want to loop yourself, then either of:
bool has = arr.Contains(var); // .NET 3.5
or
bool has = Array.IndexOf(arr, var) >= 0;
For info: avoid names like var — this is a keyword in C# 3.0.
jcolebrand
16.3k11 gold badges75 silver badges121 bronze badges
answered Nov 5, 2008 at 12:16
Marc GravellMarc Gravell
1.0m261 gold badges2552 silver badges2888 bronze badges
Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
answered Nov 5, 2008 at 13:56
TamirTamir
2,50516 silver badges23 bronze badges
2
Does it have to be a string[] ? A List<String> would give you what you need.
List<String> testing = new List<String>();
testing.Add("One");
testing.Add("Two");
testing.Add("Three");
testing.Add("Mouse");
bool inList = testing.Contains("Mouse");
answered Nov 5, 2008 at 12:18
ZombieSheepZombieSheep
29.5k12 gold badges66 silver badges114 bronze badges
bool exists = arr.Contains("One");
answered Nov 5, 2008 at 12:19
mohammednmohammedn
2,9263 gold badges23 silver badges30 bronze badges
0
I think it is better to use Array.Exists than Array.FindAll.
answered Mar 26, 2010 at 11:53
0
Its pretty simple. I always use this code to search string from a string array
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
return true;
}
else
{
return false;
}
answered Nov 6, 2013 at 10:15
If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.
answered Nov 5, 2008 at 12:19
GvSGvS
51.9k16 gold badges101 silver badges139 bronze badges
Each class implementing IList has a method Contains(Object value). And so does System.Array.
answered Nov 5, 2008 at 12:18
VolkerKVolkerK
95.2k20 gold badges163 silver badges226 bronze badges
1
Why the prohibition «I don’t want to use any looping»? That’s the most obvious solution. When given the chance to be obvious, take it!
Note that calls like arr.Contains(...)
are still going to loop, it just won’t be you who has written the loop.
Have you considered an alternate representation that’s more amenable to searching?
- A good Set implementation would perform well. (HashSet, TreeSet or the local equivalent).
- If you can be sure that
arr
is sorted, you could use binary search (which would need to recurse or loop, but not as often as a straight linear search).
answered Nov 5, 2008 at 12:57
bendinbendin
9,3941 gold badge39 silver badges37 bronze badges
You can use Find method of Array type. From .NET 3.5 and higher.
public static T Find<T>(
T[] array,
Predicate<T> match
)
Here is some examples:
// we search an array of strings for a name containing the letter “a”:
static void Main()
{
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, ContainsA);
Console.WriteLine (match); // Jack
}
static bool ContainsA (string name) { return name.Contains ("a"); }
Here’s the same code shortened with an anonymous method:
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, delegate (string name)
{ return name.Contains ("a"); } ); // Jack
A lambda expression shortens it further:
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, n => n.Contains ("a")); // Jack
answered Nov 7, 2014 at 14:09
Yuliia AshomokYuliia Ashomok
8,2162 gold badges60 silver badges69 bronze badges
At first shot, I could come up with something like this (but it’s pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?
int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
{
if currentIndex > stringMaxIndex
return (-stringMaxIndex-1);
else if var==arr[currentIndex] //or use any string comparison op or function
return 0;
else
return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
}
//calling code
int index = findString(var, arr, 0, getMaxIndex(arr));
if index == -1 printOnScreen("Not found");
else printOnScreen("Found on index: " + index);
answered Nov 5, 2008 at 12:31
In C#, if you can use an ArrayList, you can use the Contains method, which returns a boolean:
if MyArrayList.Contains("One")
answered Nov 5, 2008 at 12:49
DOKDOK
32.2k7 gold badges60 silver badges92 bronze badges
1
You can check the element existence by
arr.Any(x => x == "One")
answered Dec 5, 2014 at 8:55
AhmadAhmad
8,52710 gold badges73 silver badges130 bronze badges
it is old one ,but this is the way i do it ,
enter code here
var result = Array.Find(names, element => element == «One»);
answered Jul 13, 2020 at 14:37
AliAli
1,06216 silver badges21 bronze badges
I’m surprised that no one suggested using Array.IndexOf
Method.
Indeed, Array.IndexOf
has two advantages :
- It allows searching if an element is included into an array,
- It gets at the same time the index into the array.
int stringIndex = Array.IndexOf(arr, theString);
if (stringIndex >= 0)
{
// theString has been found
}
Inline version :
if (Array.IndexOf(arr, theString) >= 0)
{
// theString has been found
}
answered Jul 26, 2020 at 19:48
Using Contains()
string [] SomeArray = {"One","Two","Three"};
bool IsExist = SomeArray.Contains("One");
Console.WriteLine("Is string exist: "+ IsExist);
Using Find()
string [] SomeArray = {"One","Two","Three"};
var result = Array.Find(SomeArray, element => element == "One");
Console.WriteLine("Required string is: "+ result);
Another simple & traditional way, very useful for beginners to build logic.
string [] SomeArray = {"One","Two","Three"};
foreach (string value in SomeArray) {
if (value == "One") {
Console.WriteLine("Required string is: "+ value);
}
}
answered Dec 24, 2022 at 19:45
BilluBillu
2,67325 silver badges47 bronze badges
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.
Serzik -1 / 0 / 0 Регистрация: 13.04.2013 Сообщений: 90 |
||||
1 |
||||
Поиск в массиве строк13.04.2014, 17:52. Показов 9085. Ответов 8 Метки нет (Все метки)
Добрый день Возник глупый вопрос. Пытаюсь сделать поис в строковом массиве не как не получается подскажите что не такк. Сам массив char *cK_Words[] = {«procedure», «case», «of», «end», «begin», «if», «than», «inherited», «Boolean», «Word», «nil»}; Пытаюсь найти это char cTest[] = {«than»};
Выдаёт что не равны в чём мой косяк
0 |
zss Модератор 13100 / 10373 / 6206 Регистрация: 18.12.2011 Сообщений: 27,739 |
||||
13.04.2014, 19:37 |
2 |
|||
сравнение строк
res равно нулю при совпадении.
1 |
-1 / 0 / 0 Регистрация: 13.04.2013 Сообщений: 90 |
|
13.04.2014, 20:53 [ТС] |
3 |
Не тоже самое возвращяет 1 такое чувство что он не идёт по массиву а тупо останавливается на 1 слове. Я думал что каждое слово это 1 индекс но вот функция sizeof мне возвращяет не 11 а 44.
0 |
BlackSpace 205 / 181 / 112 Регистрация: 15.03.2014 Сообщений: 391 |
||||
13.04.2014, 22:06 |
4 |
|||
РешениеSerzik, почему не используете класс string?
1 |
-1 / 0 / 0 Регистрация: 13.04.2013 Сообщений: 90 |
|
13.04.2014, 22:21 [ТС] |
5 |
Спасибо просто указатель для меня в новинку тока не давно стал изучать с++
0 |
205 / 181 / 112 Регистрация: 15.03.2014 Сообщений: 391 |
|
13.04.2014, 23:03 |
6 |
Serzik, рекомендую взять популярную книгу по C++ и прочесть, выполняя примеры из книги. Добавлено через 6 минут
0 |
-1 / 0 / 0 Регистрация: 13.04.2013 Сообщений: 90 |
|
13.04.2014, 23:04 [ТС] |
7 |
Спасибо почетаю. Вот такой возник вопрос по твоему коду когда совпадения есть то всё ок когда совпадений нет он не проверяет конец строки и вылетает окно с ошибкой после чего программа завершается
0 |
205 / 181 / 112 Регистрация: 15.03.2014 Сообщений: 391 |
|
13.04.2014, 23:09 |
8 |
У меня нет никаких ошибок и при совпадении и без совпадений.
совпадений нет он не проверяет конец строки и вылетает окно с ошибкой после чего программа завершается Скриншот с ошибкой покажите.
1 |
-1 / 0 / 0 Регистрация: 13.04.2013 Сообщений: 90 |
|
13.04.2014, 23:18 [ТС] |
9 |
там эти слова потом подправлю мне нужно сделать сканер кторый будет сканить псевдо код и проверять если такие слова в нём или нет Добавлено через 8 минут
0 |
См. также Массивы в языке 1С 8 (в примерах)
МассивЦветов = Новый Массив(3); МассивЦветов[0] = "Красный"; МассивЦветов[1] = "Оранжевый"; МассивЦветов[2] = "Желтый"; Индекс = МассивЦветов.Найти("Оранжевый"); Если Индекс <> Неопределено Тогда Сообщить("Значение найдено " + МассивЦветов[Индекс]); КонецЕсли;
С уважением, Владимир Милькин (преподаватель школы 1С программистов и разработчик обновлятора).
Как помочь сайту: расскажите (кнопки поделиться ниже) о нём своим друзьям и коллегам. Сделайте это один раз и вы внесете существенный вклад в развитие сайта. На сайте нет рекламы, но чем больше людей им пользуются, тем больше сил у меня для его поддержки.
Нажмите одну из кнопок, чтобы поделиться:
Выполняет поиск элемента в массиве.
Синтаксис
Метод Найти()
имеет следующий синтаксис:
число Найти(Значение)
А также альтернативный англоязычный синтаксис:
number Find(Value)
Параметры
Описание параметров метода Найти()
:
Имя параметра* | Тип | Описание |
---|---|---|
Значение | Произвольный | Значение, которое нужно найти |
*Жирным шрифтом выделены обязательные параметры |
Возвращаемое значение
Число |
— индекс первого найденного элемента массива |
Неопределено |
— если элемент не был найден |
Описание
Метод Найти()
выполняет поиск заданного элемента в массиве. Если элемент не найден, метод возвращает Неопределено.
Важно! Метод эффективно использовать для поиска уникальных значений
Доступность
Тонкий клиент, веб-клиент, мобильный клиент, сервер, толстый клиент, внешнее соединение, мобильное приложение(клиент), мобильное приложение(сервер).
Пример использования
Пример кода с использованием метода Найти()
:
м = Новый Массив; ... элт = м.Найти(1); Если элт = Неопределено Тогда м.Добавить(1); КонецЕсли; элт = м.Найти(2); Если элт = Неопределено Тогда м.Добавить(2); КонецЕсли; ...
Поделиться страницей в соц.сетях