Code covered by the BSD License  

Highlights from
String comparison

2.0

2.0 | 1 rating Rate this file 14 Downloads (last 30 days) File Size: 1.23 KB File ID: #43064

String comparison

by

 

14 Aug 2013 (Updated )

The function searches for a string inside a given target and returns 1 for found or 0 for not found.

| Watch this File

File Information
Description

The function searches for a string inside a given target string and returns 1 for found or 0 for not found.

The format can be either cell or string.

Example:

target = 'Marc goes fishing'
searchterm = 'goes'

The function will return 1.

MATLAB release MATLAB 8.1 (R2013a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (3)
16 Aug 2013 Christian

Thanks Richard and Jan for your comments. I included your suggestions and updated the code.

15 Aug 2013 Jan Simon

It is essential for reliable programs, that they stop in case of errors. Therefore "error()" is much better than "disp()" in case of not matching inputs. When the lean documentation explains, that the search-term must be a string, accepting a cell string is not apropriate.

Richard's suggestion to use STRFIND is important. I'd suggest:

function result = strcompare(target,searchterm)
if ischar(target)
result = any(strfind(target, searchterm);
elseif iscellstr(target)
result = ~cellfun('isempty', strfind(target, searchterm));
else
error('1st input must be a string or cellstring');
end

15 Aug 2013 Richard Crozier

This can be replaced with

~isempty(strfind(str, substr))

or for your example

>> ~isempty(strfind('Marc goes fishing', 'goes'))

ans =

1

strfind also works for cell arrays

>> strfind({'Marc goes fishing', 'banafdsafas'}, 'goes')

ans =

[6.0000e+000] []

so could be adapted for your other use cases. It will be much faster than your loopy code, which is also inefficient in other ways.

Updates
19 Aug 2013

Included the suggestions of Richard and Jan. No loops anymore and I included an error message.

Contact us