function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RajusRajus 

Extract substring from a string.

Hi All,

I have one list some thing like below.
List<string> possiblevalues = new list<string>{'abc gh', 'def', 'ghi'};

and One string some thing like below
String str = 'Hello guys Hello world abc gh ';

Now i have to look for each string of possiblevalues in str.Is there any simple method to find out whether the string is present in the str or not.
I know the simple way which is,

for(string s:possiblevalues)
{
       if(str.contains(s);
            string matchvalue = s;

}
But this technique will loop through all elements of list.But i need more efficient way without using for loops for this.


If some one find the better approach pleas let me know.


Thanks,
Raj.
Subramani_SFDCSubramani_SFDC
can u try this and check it iwill work.....

Set<String> keyWords = new Set<String>{'dog','cat','pat'};
if(JSON.serialize(keyWords).contains('dog'))
{
    System.debug('It contains dog!');
}
Abhi_TripathiAbhi_Tripathi
Hey,

rather then taking a list , you can take a set because set have the method "Contains"

Set<string> possiblevalues = new Set<string>{'abc gh', 'def', 'ghi'};

String str = 'Hello guys Hello world abc gh ';

//Split the str at Spaces ' '
List<String> splittedStr = str.split(' ');

 
//Loop through the List of Str
for(String st : splittedStr) {
 
 //Check weather set contains or not
if(
possiblevalues.contains(st)) {
String matchinStr = st;
}
}
 
Regards,
Abhi Tripathi
Salesforce Developer
RajusRajus
Hi,

Thanks for quick reply.

Here my actual requirement is to look whether any of the set element contains in the actual string and i dont want to loop through each set element.

Also i cannot split the string based on space(' ').Bcoz Set elements may contains the strings with spaces or without spaces.

For ex:
String actualstring = 'Hello guys Hello world abc gh ';
Set<string> searchvalues = new Set<string>{'abc gh', 'def', 'ghi'};


In this set the first element is 'abc gh' and it contains a space.

Now i have to search for this string in the Actual string.If it contains that string in actual string i have to assign it to a new string.
Likewise i have to look for remaining set elements in the actualstring without running the for loop.Bcoz my set may have thousands of elements.


Please let me know if there is any simple method for my requirement.



Thanks,
Raj.