Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Matlab中的字符串startWith_String_Matlab Deployment - Fatal编程技术网

String Matlab中的字符串startWith

String Matlab中的字符串startWith,string,matlab-deployment,String,Matlab Deployment,我只想知道字符串的开头,是否有一个等价的matlab允许这样说:startsWith('It-is')like in java 谢谢您可以使用该函数判断一个字符串是否以另一个字符串开头。函数返回要查找的字符串的每次出现的起始索引,如果找不到该字符串,则返回空数组 S = 'Find the starting indices of the pattern string'; strfind(S, 'It-is') 如果字符串以'It-is'开头,则strfind返回的数组的第一个索引将是1(即第一

我只想知道字符串的开头,是否有一个等价的matlab允许这样说:startsWith('It-is')like in java

谢谢

您可以使用该函数判断一个字符串是否以另一个字符串开头。函数返回要查找的字符串的每次出现的起始索引,如果找不到该字符串,则返回空数组

S = 'Find the starting indices of the pattern string';
strfind(S, 'It-is')

如果字符串以
'It-is'
开头,则
strfind
返回的数组的第一个索引将是1(即第一个字符的索引)。

对于长字符串,这样做更快

s = (numel(a)>=numel(b)) && all(a(1:min(numel(a),numel(b)))==b(1:min(numel(a),numel(b))));

为了使a.startsWith(b)

等效于
a.startsWith(b)
,strfind的问题在于它返回一个非标量结果,这限制了您可以使用它的位置。更直截了当的是这样使用


我想补充一点,如果s是单元格,那么regexp和strfind返回a。
在这种情况下,您可以使用两种变体之一:

pos = strfind(s, 'It-iss');
if (~isempty(pos{1,1}))
    disp('s starts with "It-is"')
end


不能直接将
regexp
strfind
的返回值强制转换为bool,因为如果没有匹配项,
regexp
strfind
返回一个空单元格
{[]}
。要访问第一个单元格,您需要使用带括号的操作符
pos{1,1}

最适合我的选项是:

~isempty(regexp(s, '^It-is', 'once')) 
~isempty允许将表达式与逻辑or或AND一起使用,如下所示:

if ~isempty(regexp(s, '^It-is', 'once')) || ~isempty(regexp(s, '^It-was', 'once')) 

“once”参数是一种优化,以确保在开始时找到匹配项后不会继续扫描字符串。

从Matlab2016b开始,有一个函数:

startsWith(your_string, 'It-is')
matches = strfind(your_string, 'It-is');
string_starts_with_pattern = ~isempty(matches) && matches(1) == 1;
在以前的版本中,您可以使用来创建自己的功能:

startsWith(your_string, 'It-is')
matches = strfind(your_string, 'It-is');
string_starts_with_pattern = ~isempty(matches) && matches(1) == 1;

我不同意这个评论——您可以总是将
strfind
包装在
isempty
中以获得布尔值。同样值得注意的是,
regexp
的MATLAB实现要比
strfind
@mbroshi慢得多,不,你不能
isempty(strfind(s,regexp)
始终为真,因为strfind在未找到匹配项时返回
{[]}
。因为
如果regexp(s,“^it is”)
给出错误:>“无法从单元格转换为逻辑单元格”我不知道你为什么说它会出错。我只是在最新的MATLAB中确认了这一点,并按预期输出。
>s='这是真的。;如果regexp(s,^it is')disp('s以“it is”开头)end
输出:s以“it is”开头
在示例中,s不是单元格。能否提供遇到错误的上下文?