File Exchange

image thumbnail

Class for character array

version 1.3 (7.09 KB) by

Class for easier string manipulation, with many operators and functions overloads.

0 Downloads

Updated

View License

Create a new type called STR with a character array inside, implemented as a structure. It was inspired in Visual Basic syntax.
It was implemented several operators and functions overloads, but allows any character array function using "char" conversor function or ' transpose overload.
It's necessary to create a folder from a MatLab folder in one of the MatLab paths. The folder name is class name, with @ prefix. The .m name is class name.

Operator Overload: ==,~=,<=,>=,>,< -,*,/,\,', [], +,-, (), |
Function Overload: disp, length, upper, lower, strfind
Other Functions: str, left, right, mid, padl,padr, padc, instr, repeat, replace, trim, ltrim, rtrim

Example
=======
s1=str('play');
s1-'l'+ ' t' + 'cricket' - 'cr'
ans=
pay ticket

More details in the start of str.m file and before each function.

Comments and Ratings (2)

Cris Luengo

Thanks for your comments.
It's was very useful for making a "best class" character array handling.

I've submitted a updated version.

Cris Luengo

Cris Luengo (view profile)

I like being able to compare strings with the comparison operators! The code you wrote for comparisons is very much in the Basic style, not so much in the MATLAB style. You'll find that this function is faster:

function r = compare_strings(a,b)
% returns: 0 == equal
% 1 == a is larger
% -1 == b is larger
a = str(a); a = a.s;
b = str(b); b = b.s;
la = length(a);
lb = length(b);
l = min(la,lb);
r = a(1:l)-b(1:l);
[~,~,r] = find(r,1,'first');
if ~isempty(r)
r = sign(r);
else % they're equal, compare lengths
if la==lb
r = 0;
elseif la<lb
r = -1;
else
r = 1;
end
end
end

function r = lt(a,b)
r = compare_strings(a,b)<0;
end

(etc.)

Whenever you have two or more 'str' inputs, it is nice to convert those inputs to class 'str' explicitly. That way, it is possible to mix an object of class 'str' with a different class, for example:
a=str('hello')
a < 'goodbye'

If you do a similar conversion for the '[]' and '+' operation, you can do something like:
a=str('hello')
a = [' ',a,' ',5]

I would also overload the '*' as your 'repeat' function. Makes sense to me:
str('hello')*5

You also need to overload 'cat' and 'vertcat' methods. Rigth now, you get an error when you do [a;a]. It creates an object with 2 strings in it, which the 'disp' function cannot display.

Updates

1.3

Minor bugs correction. Improving functions. Adding ', |, - operator overloading.

1.2

Minor bug corrections, Improves heuristics and introduces new *, / and \ operators.

1.1

Minor bug corrections and left assignment for Str

MATLAB Release
MATLAB 7.9 (R2009b)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video