如何统计字符串中所有重叠的子串?

问题描述 投票:0回答:1

我有一个字符串变量,代表对象随时间的情绪变化,如 1,2 或 3。作为示例,它可能如下所示:

主题 心情
阿尔伯特 112132
贝蒂 111213

我需要了解他们改变了多少措施与保持不变,以及如何改变。

我的第一次尝试是计算子字符串,例如:

STATIC_11 = count(心情,”11”);

但是,这不起作用(正如 count 函数文档所警告的那样),因为“如果指定子字符串在字符串中出现两次重叠,将返回不一致的结果。”

例如,在 Betty 的情况下,我希望她的 static_11 始终 = 2,因为心情中的初始字符串“111”代表她的心情为 1 的 2 倍,而之前的心情为 1。

Mood 是一个字符变量,非空白长度为 1-9。我真的不想自己手动识别所有可能的子字符串,尽管我认为这在技术上是一个解决方案。

string count sas
1个回答
0
投票

实现此目的的一种方法是使用 do 循环遍历字符串的长度,从 2 开始,并使用 substr() 将每个字符与前一个字符进行比较以提取子字符串。

这段代码的完整功能是:

  • 设置计数器变量来存储变化与静态计数
  • 使用命名变量设置可能的分数变化的二维数组
  • 逐字符循环情绪字符串,检查当前与上一个字符以填充数组并增加更改和静态计数
data want;
input Subject $ Mood : $32.;
moodlength = length(mood);
/* Set up variables to */
mood_change = 0;
mood_static = 0;
array changes (3,3) static_11 change_12 change_13 
                    change_21 static_22 change_23 
                    change_31 change_32 static_33;

/* Empty the changes array for the next row */
do i = 1 to 3; do j = 1 to 3; changes(i,j)=0; end;end;

do i = 2 to length(mood);
  prev_mood = input(substr(mood,i-1,1),1.);
  curr_mood = input(substr(mood,i,1),1.);

  /* Increment the counter for the specified score change */
  changes(prev_mood,curr_mood)+1;

  /* Check the previous mood with current and count change vs static */
  if substr(mood,i-1,1) = substr(mood,i,1) then mood_static+1;
  else mood_change+1;

end;

/* Remove temporary variables */
drop i j prev_mood curr_mood;

/* Play with sample data here or use a set statement for an input dataset */
datalines;
Albert 112132132313131311231
Betty 1113
;
proc print;
run;

© www.soinside.com 2019 - 2024. All rights reserved.