C# - check if substring is present in arraylist of strings

C# - check if substring is present in arraylist of strings

By : Chamil Udayanga
Date : October 22 2020, 08:10 PM
Hope that helps If you want only to print the first string that contains the search, you can use FirstOrDefault():
code :
var foundString =  arr1.OfType<string>().FirstOrDefault(arg => arg.Contains("String2"));
Console.WriteLine(string.IsNullOrEmpty(foundString) ? "Not found" : foundString);

Share : facebook icon twitter icon
Efficient way of finding all strings of an Arraylist, which contains a substring

Efficient way of finding all strings of an Arraylist, which contains a substring

By : user3596753
Date : March 29 2020, 07:55 AM
Hope that helps Hey as you want some optimized solution so you can try this :
sort the list with help of Collections.sort(list); find for first matching string with help of binary search and make flag that string with this prefix found. now if next string doesnot match this prefix that means no next string of list will match this prefix as we have sorted the collection
code :
package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class T { 
    static int count=0;     
    public static void main(String[] args) {    
        List<String> list = new ArrayList<String>();

       // for testing purpose only i am making this list and putting this data
        for (int i = 101; i < 501; i++) {
            list.add(i + "");
        boolean matchedSuffix = false;
        String prefix = "30";


        int startFrom = T.binarySerchOverList(list, prefix);

        if (startFrom == -1) {
            System.out.println("no data found");
        } else {
                for (int i = startFrom;; i++) {
                String s = list.get(i);
                if (s.startsWith(prefix)) {                     
                    //here you will get matching strings                    
                    matchedSuffix = true;
                } else {
                    if (matchedSuffix) {


    public static int binarySerchOverList(List<String> input, String prefix) {    
        System.out.println( "iteration count is "+count);       
        int size = input.size();
        int midpoint = size / 2;
        int startPoint = 0;

        String stringToTest = input.get(midpoint);
        if (stringToTest.startsWith(prefix)) {
            startPoint = midpoint - 1;
            while (true) {

                if (!input.get(startPoint).startsWith(prefix)) {
                if (startPoint == 0) {
            return startPoint;

        if (stringToTest.compareTo(prefix) > 0) {
            List<String> sublist = input.subList(0, midpoint);
            return binarySerchOverList(sublist, prefix);

        if (stringToTest.compareTo(prefix) < 0) {    
            if (input.get(input.size() - 1).compareTo(prefix) < 0) {
                return -1;
            List<String> sublist = input.subList(midpoint, input.size());
            return binarySerchOverList(sublist, prefix);
        return 0;    
java - check if a substring is present in an arraylist of strings in java

java - check if a substring is present in an arraylist of strings in java

By : Chuan Tian
Date : March 29 2020, 07:55 AM
hop of those help? You cannot use contains method of ArrayList, because you cannot get around checking each string individually.
In Java 8 you can hide the loop by using streams:
code :
boolean found = arr1.stream().anyMatch(s -> s.contains("string2"));
Removing Strings if Substring of the String is Present in Same Array

Removing Strings if Substring of the String is Present in Same Array

By : iKay
Date : March 29 2020, 07:55 AM
wish help you to fix your issue First, a solution based strictly on shared domain names (e.g., helpx.adobe.com and adobe.com are considered to belong to the same domain, but list-manage.com and manage.com are not). This is not what you asked for, but perhaps more useful to future readers:
code :
Get-Content parent.txt | Sort-Object -Unique { ($_ -split '\.')[-2,-1] -join '.' }
# Helper function for (naively) reversing a string.
# Note: Does not work properly with Unicode combining characters
#       and surrogate pairs.
function reverse($str) { $a = $str.ToCharArray(); [Array]::Reverse($a); -join $a }

# * Sort the reversed input lines, which effectively groups them by shared suffix
#   with the shortest entry first (e.g., the reverse of 'manage.com' before the
#   reverse of 'list-manage.com').
# * It is then sufficient to output only the first entry in each group, using
#   wildcard matching with -notlike to determine group boundaries.
# * Finally, sort the re-reversed results.
Get-Content parent.txt | ForEach-Object { reverse $_ } | Sort-Object |
  ForEach-Object { $prev = $null } {
    if ($null -eq $prev -or $_ -notlike "$prev*" ) { 
      reverse $_ 
      $prev = $_
  } | Sort-Object
Test that a substring is present in array of strings in rspec

Test that a substring is present in array of strings in rspec

By : Glenn Smith
Date : March 29 2020, 07:55 AM
With these it helps RSpec offers a range of matchers. In this case you'll need to use the include matcher (docs) to check each element of the array. And, you'll need to use the match regex matcher (docs) to match the substring:
code :
expect(json[:errors]).to include(match(/can't be blank/))
expect(json[:errors]).to include(a_string_matching(/can't be blank/))
How to check if an ArrayList of Strings contains substrings of another ArrayList of Strings?

How to check if an ArrayList of Strings contains substrings of another ArrayList of Strings?

By : user5927353
Date : March 29 2020, 07:55 AM
I wish this helpful for you , How about something like this:
code :
list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)))
boolean allMatch = true;       // Start allMatch at true
for(String s1 : list1){
  boolean anyMatch = false;    // Start anyMatch at false inside the loop
  for(String s2 : list2){
    anyMatch = s1.contains(s2);// If any contains is true, anyMatch becomes true as well
    if(anyMatch)               // And stop the inner loop as soon as we've found a match
  allMatch = anyMatch;         // If any anyMatch is false, allMatch becomes false as well
  if(!allMatch)                // And stop the outer loop as soon as we've found a mismatch
return allMatch;
public final class CollectionsUtil{
  public static boolean containsAny(ArrayList<String> list1, ArrayList<String> list2){
    return list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)));
    // Or the contents of the Java 7 check-method above if you prefer it

  private CollectionsUtil(){
    // Util class, so it's not initializable
boolean result = CollectionsUtils.containsAny(actualList, expectedList);
Related Posts Related Posts :
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • .NET listbox to SQLite DB
  • C# Ninject binding from Dictionary<Type, Type>
  • asp.net mvc -view displaying real-time progress status
  • Getting reference to dependent in service with generic type
  • Implementing EqualityCompare vs overriding GetHashCode and Equals
  • C# Linq Find all indexes of item in List<int> within another List<int>
  • XML image how to display at data grid columns in c#.net
  • How to override Equals and GetHash of HashSet
  • Creating Windows authentication and SQL Server authentication in login form
  • How to interop with Azure Service Bus topics created by MassTransit using Rebus?
  • MVC 5 Google Calendar Integration
  • C# - Use parallel arrays to calculate cost of a phone call in GUI
  • Use a int in entire code
  • How to display newly added element at the top of StackPanel in WPF?
  • T4MVC is generating T4MVC.cs and T4MVC1.cs
  • Remove blur effect on certain controls inside UserControl
  • Sql Transcation Query to Linq Query in Wcf Rest Service
  • Setting AWS S3 credentials in C# app
  • does not contain in an ObservableCollection
  • App doesn't run it crashed directly after I started it
  • Is it possible in Entity Framework MVC application to run .sql scripts on a different database
  • Type Inference with Deconstruct tuple assignment extension methods
  • Setting up mock objects for EF dbcontext to test repository methods
  • Using C# in XSLT with MSXSL 6.0
  • Absolute positioning of UIElement in FlowDocument in WPF
  • Display debuggers not showing up in Visual Studio 2017
  • Discord.NET Users playing the same game
  • Azure function output API call to 3rd party service
  • Unable to determine the relationship represented by navigation property ASP.NET core 2.0 Entity Framework
  • Regex to find group of Regex inside a word
  • When calling a method, when to reference the class, and when to reference the object?
  • AmazonCloudWatchLogsClient async methods failing with no error
  • Create FileStream in memory instead of saving a physical file on disk
  • ViewBag data coming from ActionFilter is persisting in session even after database
  • ERROR: the name 'lvSubCategories' does not exist in the current context
  • Why datetime can't recognise the string?
  • Getting 500 error while requesting to webservice using Ajax AutoCompleteExtender
  • The property 'x' is not a navigation property of entity type 'y'
  • ASP.NET MVC - How to generate empty input boxes in loop when model is empty?
  • Need help writing regular expression
  • Add/remove buttons to a panel with an arraylist c#
  • Linq .Where(type = typeof(xxx)) comparison is always false
  • Using EF6 Code First without migrations to an existing db how do I specify column names of the many to many join table?
  • C# - Using Thread.Sleep precisely in a console application
  • Add item to a List<Tuple> inside another list
  • Double[,], inversion C#
  • Counting a string to ensure the input is within a min/max boundary
  • Assign invalidValue to Enum variable (why is this not throwing an Exception?)
  • Namespace or type specified in the project-level Imports 'System.Threading.Tasks' doesn't contain any public member or c
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org