数学建模社区-数学中国
标题: 字符串比较函数---2 [打印本页]
作者: 森之张卫东 时间: 2015-9-24 22:31
标题: 字符串比较函数---2
字符串比较函数---2
4. 把算法转化为相应的MATLAB语句
function result = c_strcmp(str1,str2)
%C_STRCMP Compare strings like C function "strcmp"
% Function C_STRCMP compares two strings, and returns
% a -1 of str1 < str2, a 0 if str1 == str2, and a
% +1 if str1 > str2.
% Define variables:
% diff -- Logical array of string differences
% msg -- Error message
% result -- Result of function
% str1 -- First string to compare
% str2 -- Second string to compare
% strings -- Padded array of strings
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 10/18/98 S. J. Chapman Original code
% Check for a legal number of input arguments.
msg = nargchk(2,2,nargin);
error(msg);
% Check to see if the arguments are strings
if ~(isstr(str1) & isstr(str2))
error('Both str1 and str2 must both be strings!')
else
% Pad strings
strings = strvcat(str1,str2);
% Compare strings
diff = strings(1,
~= strings(2,
; if sum(diff) == 0
% Strings match, so return a zero!
result = 0;
else
% Find first difference between strings
ival = find(diff);
if strings(1,ival(1)) > strings(2,ival(1))
result = 1;
else
result = -1;
end
end
end
5. 检测程序
我们必须用多个字符串对程序进行检测
>> result = c_strcmp('String 1','String 1')
result =
0
>> result = c_strcmp('String 1','String 1 ')
result =
0
>> result = c_strcmp('String 1','String 2')
result =
-1
>> result = c_strcmp('String 1','String 0')
result =
1
>> result = c_strcmp('String 1','str')
result =
-1
第一次检测返回0,是因为两字符串是相同的。第二次也返回0,因为两字符串也是相等的,只是末端空格不同,末端空格被忽略。
第三次检测返回-1,因为两字符串第一次的不同出现在第8位上,且在这个位置上“1”<“2”。第四次检测将返回1,因为两字符串第一次的不同出现在第8位上,且在这个位置上,“1”>“0”。第五次检测将会返回-1,因为两字符串的第一个字符就不同,在ascii的序列上“S”<“s”。这个函数工作正常。
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) |
Powered by Discuz! X2.5 |