+ Start a Discussion

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)
            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.

can u try this and check it iwill work.....

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

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
possiblevalues.contains(st)) {
String matchinStr = st;
Abhi Tripathi
Salesforce Developer

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.