简体   繁体   English

检查字符串是否在Octave中包含三个相同的字母

[英]Check if string contains three same letters in Octave

I'm trying to make a function in Octave to check whether a string contains three consecutive same characters. 我正在尝试在Octave中创建一个函数来检查字符串是否包含三个连续的相同字符。 That is, if my string is "asdf" it should return 0 and if it's like "asdfffg" it should return 1. What I did so far is this 也就是说,如果我的字符串是"asdf"它应该返回0 ,如果它像"asdfffg"则返回1.我到目前为止所做的是这个

if(length(findstr(word,"aaa",0)) > 1 || length(findstr(word,"bbb",0)) > 1 ||   ..

It's costly and I think not that really inefficient. 这是昂贵的,我认为不是真的低效。 Any suggestions? 有什么建议么?

Use a regular expression : 使用正则表达式

match = regexp(word, '(.)\1{2}', 'once');

This means: match any character ( (.) ), followed by that same character ( \\1 ) twice ( {2} ). 这意味着:匹配任何字符( (.) ),然后匹配相同的字符( \\1 )两次( {2} )。 It will return the starting index of the first match, or an empty array if there isn't any match. 它将返回第一个匹配的起始索引,如果没有匹配则返回一个空数组。 So your desired result would be 所以你想要的结果就是

result = ~isempty(match);

Another possibility is to use convolution : 另一种可能性是使用卷积

result = any(conv([1 1], +~diff(word))==2);

This works as follows: diff will give 0 when two consecutive characters are the same. 其工作原理如下:当两个连续的字符相同时, diff将给出0 So you want to detect if the output of diff contains two consecutive zeros. 所以你想检测diff的输出是否包含两个连续的零。 This is done by negating ( ~ ), converting to double ( + ), convolving with the sequence [1 1] ( conv([1 1], ...) ), and seeing if 2 is present in the output. 这是通过否定( ~ ),转换为double+ ),与序列[1 1]conv([1 1], ...)进行卷积,并查看输出中是否存在2来完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM