String starts with anything in a set?
String starts with anything in a set<String>?
I want to see if any of the strings I pass(num) starts with any of the values on my set
Ex. String num = 456987533;
Set<String> numValidator = new Set<String>‘456’,’312’,762’;
Since my num starts with ‘456’ it should come back true.
How can I write this out?
StartsWith does not work because it is only comparing a string and not a set
1 Answer
1
Unless all of your String prefixes are the same length, you'll need to iterate over the contents of your Set.
for (String s : numValidator)
if (myInputString.startsWith(s))
// do something
However, if all of your prefixes are exactly three characters, you can handle this more simply and make use of Set membership constant-time checking:
Set<String> numValidator = new Set<String>'456','312','762';
String myInputString = '312456';
if (numValidator.contains(myInputString.left(3)))
System.debug('Found it');
numValidator
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
One more creative option would be to turn
numValidator
into a regex pattern and look for matches against the input string.– Mark Pond
Aug 29 at 17:10