Code covered by the BSD License  

Highlights from
String comparison

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

String comparison

by

Christian (view profile)

 

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

Christian (view profile)

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

Comment only
15 Aug 2013 Jan Simon

Jan Simon (view profile)

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.

Comment only
Updates
19 Aug 2013 1.1

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

Contact us