Tags down


finding a substring in a list of strings

By : Corny_Coder
Date : September 17 2020, 07:00 AM
fixed the issue. Will look into that further You can check whether All keywords match in Any item of your wordset that might String.Contains your key word
code :
List<string> keyWords = new List<string>{"issue","resolution","rootfix"};

List<string> wordSet = new List<string>{"issue: there are multiple data errors ", "resolution: you can correct the data or /n raise an SR on this issue", "rootfix: you need to be contious while entering the data "};

bool result = keyWords.All(x => wordSet.Any(w => w.Contains(x)));

Share : facebook icon twitter icon

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;    

Finding substring in list of strings, return index

By : flaire_allisson sala
Date : March 29 2020, 07:55 AM
this will help I don't think there is a good (i.e. readable) one-line solution for this. Alternatively to @eugene's loop, you could also use a try/except.
code :
def get_index(list_of_strings, substring):
        return next(i for i, e in enumerate(list_of_strings) if substring in e)
    except StopIteration:
        return len(list_of_strings) - 1
next((i for i, e in enumerate(list_of_strings) if substring in e), 
     len(list_of_strings) - 1)

Finding *modal* substring of a list of strings in python

By : Emma Higgins
Date : March 29 2020, 07:55 AM
Hope this helps Finding a common substring has been answered in many questions, i.e. given a list of strings find the (typically longest or largest number of words) substring that is common to all of them. See here: , Finding modal substring of given length
Our input is as follows:
code :
mylist = ["hey how's it going?", "I'm fine  thanks.", "Did you get that thing?", "Of course I got that thing, that's why I asked you: how's it going?"]
def preprocess(strings):
    # used this answer to get rid of extra whitespaces: https://stackoverflow.com/a/1546251/6735980
    return [" ".join(string.split()).replace(",", "").replace(".", "").replace("?", "") for string in strings]
def find_n_grams(string, n):
    words = string.split(" ")
    n_grams = []

    for i in range(len(words) - n + 1):
        n_grams.append(" ".join([words[i + idx] for idx in range(n)]))

    return n_grams
def find_modal_substring(strings, num_words):
    n_grams_per_string = [find_n_grams(string, num_words) for string in strings]
    max_num_occurences = 0
    modal_substring = None

    for i in range(len(strings)):
        n_grams = n_grams_per_string[i]

        for n_gram in n_grams:
            num_occurences = 1

            for j in range(i + 1, len(strings)):
                if n_gram in n_grams_per_string[j]:
                    num_occurences += 1

            if num_occurences > max_num_occurences:
                max_num_occurences = num_occurences
                modal_substring = n_gram
            elif num_occurences == max_num_occurences and len(modal_substring) < len(n_gram):
                max_num_occurences = num_occurences
                modal_substring = n_gram

    return modal_substring
> print(find_modal_substring(preprocess(mylist), 3))
> print(find_modal_substring(preprocess(mylist), 2))
def compute_score(n_gram, occurences, alpha):
    return alpha * len(n_gram.split(" ")) + (1.0 - alpha) * occurences
def find_modal_substring_alpha(strings, alpha):
    n_grams_per_n_per_string = []
    n = 1

    while True:
        n_grams_per_string = [find_n_grams(string, n) for string in strings]

        if all(n_grams == [] for n_grams in n_grams_per_string):

        n += 1

    best_modal_substring = None
    best_score = 0.0

    for n_grams_per_string in n_grams_per_n_per_string:
        for i in range(len(strings)):
            n_grams = n_grams_per_string[i]

            for n_gram in n_grams:
                num_occurences = 1

                for j in range(i + 1, len(strings)):
                    if n_gram in n_grams_per_string[j]:
                        num_occurences += 1

                score = compute_score(n_gram, num_occurences, alpha)

                if score > best_score:
                    best_score = score
                    best_modal_substring = n_gram
                elif score == best_score and len(best_modal_substring) < len(n_gram):
                    best_score = score
                    best_modal_substring = n_gram

    return best_modal_substring
> print(find_modal_substring_alpha(preprocess(mylist), 0.3))
> print(find_modal_substring_alpha(preprocess(mylist), 0.01))

Finding the First Common Substring of a set of strings

By : ThalesBa
Date : March 29 2020, 07:55 AM
With these it helps There are quite a few steps to do this.
Remove Punctuation Break down Sentences into list of Words Create string of all combinations of contiguous words (min:1, max:wordCount) Join the three lists on new list of string (subsentences) Sort Accordingly.

Python: Finding a substring within a string from a list, but saving the substring

By : lexapopoli
Date : March 29 2020, 07:55 AM
hop of those help? Basically, I have a list of substrings I am searching a string for. I'm using any() currently and doing some work if one of the words are found in the string. I want to start logging the matches to keep some stats on the matches. I am using any() right now. , Let's look at this example:
Related Posts Related Posts :
  • Cannot locate xaml page in my WPF MVVM application
  • How can i use my IUnitOfWork with a BaseController
  • I have a problem in ASP.NET & C#: after I successfully save a record
  • IQueryable vs IEnumerable - how many DB calls?
  • Dotnet core 3.1 version of RelationalMetadataExtensions.Relations()
  • Why instance methods can't be called as static methods
  • create c# .dll compatible on both .net3.5 and .net4.0
  • HttpRequest.RouteValues property is not accessible from code but accessible from debugger
  • How to generate .tlh file for the C# project
  • How to debug a WPF application deployed with ClickOnce?
  • Array of ints - does not exist in the current context
  • How to return a dynamic object list from web api in c#
  • Converting sql to LINQ C#
  • Why is the CS0120 error showing up? I cant figure it out
  • Is there way to use extension methods to achieve below implementation in C#?
  • Two constructors in one class C#
  • C# remove line using regular expression, including line break
  • WCF Enum By Value Surrogates to support dynamic enums
  • Call c# executable in c++ managed and run asynchronously
  • C# lambda filter by condition in sublist
  • c# deserialization exception InvalidOperationException: <ArrayOf xmlns=''> was not expected. How to import array f
  • How to write window event log by order
  • To obtain date value from the SQL Server database using linq in C#
  • Biometrics Fingerprint is giving somebody else's information
  • How can I make my app send out notifications when it's loaded but not running in the foreground?
  • Where do i put the } symbol?
  • How do I use AOP for Blazor assemblies
  • Multiple entities to same DbSet
  • Async task deadlocks if task is extracted first
  • How to initialize a scoped injected class in ASP.NET Core involving asynchronous calls
  • C# worker service vs windows service
  • C# Protobuf Deserialization
  • Is it possible to get only initialized properties in a C# class
  • Get list of values used on a `where` clause of a SQL Query
  • Remove redundant String from array string
  • How to Convert the Following Xml to C# Object
  • Take class which implements interface
  • Using Autofac with ASP.Net Core 3.1 generic host "Worker Service" application
  • Combine first character with every other of a word
  • when "nwserver.exe" stops, it doesn't launch the second program in c#
  • why Firebase in C# form app not realtime?
  • Add double quotes to variable name for MS Deploy code in c#
  • ConfigureAwait(true) in library
  • Can you always Invoke instead of checking InvokeRequired?
  • C# out of scope objects not getting collected
  • Input for block breaker game
  • Can .net micro framework project upgrade to .net core?
  • Callback from C++ to C# using SWIG
  • Memory leak in .NET Core 3.0 app when using NLog or Serilog
  • Using StringBuild to change string to lowercase only for uneven positioned letters
  • A possible object cycle was detected which is not supported
  • Using Where clause in Group Join
  • Console.ReadLine() not working in VS Code, writing a code in C#
  • Expression instead of statement
  • HttpClient static with new
  • FileSystemWatcher does not notify on deleting the path directory itself
  • Disable AutoDetectChanges on Entity Framework Core
  • C# casting to parent still running child methods
  • How to solve error does not contain a definition for - new to C#
  • Trying to create Login System in C#
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk