ASS

* 定义函数:从字符串左边截取到指定字符(不包括该字符)
capture program drop ustrleft_until_char
program define ustrleft_until_char
    syntax varlist(numeric min=1 max=1) [if] [in], char(string)
    marksample touse
    tempvar result
    gen `result' = ""
    foreach v of varlist `varlist' {
        replace `result' = ustrleft(`v', strpos(`v', "`char'") - 1) if `touse'
    }
    replace `result' = "" if strpos(`varlist', "`char'") == 0 & `touse'
    return local result `result'
end


* 定义函数:从字符串左边截取到指定字符(不包括该字符)
capture program drop ustrleft_until_char
program define ustrleft_until_char
    syntax varlist(numeric min=1 max=1) [if] [in], char(string)
    marksample touse
    tempvar result
    gen `result' = ""
    foreach v of varlist `varlist' {
        replace `result' = ustrleft(`v', strpos(`v', "`char'") - 1) if `touse'
    }
    replace `result' = "" if strpos(`varlist', "`char'") == 0 & `touse'
    return local result `result'
end

* 示例数据
clear
input str20 myvar
"北京市海淀区"
"上海市浦东新区"
"广州市天河区"
"深圳市南山区"
end

* 调用函数:截取到""字前部分
ustrleft_until_char myvar, char("")

* 查看结果
list

 

posted @ 2025-12-24 14:39  myrj  阅读(4)  评论(0)    收藏  举报