从字符串中删除连续的重复字符

dzjeubhm  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(321)

我正在尝试构建一个函数,从字符串中删除重复字符。只有紧随其后的字符。例如:“aaabbbccddaabb”必须给出“dab”。我做了下面的代码,但它不工作。你能帮忙吗?我是mysql开发的新手。。。

CREATE DEFINER=`root`@`localhost` FUNCTION `REMOVE_DUPLICATE_CHAR_FROM_STRING`(myString VARCHAR(50)) RETURNS varchar(50) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
NO SQL
BEGIN
DECLARE tempString VARCHAR(50) DEFAULT '';
DECLARE sPreviousChar VARCHAR(1);
DECLARE sCurrentChar VARCHAR(1);
DECLARE inti INTEGER DEFAULT 1;
set tempString = myString;
IF LENGTH(tempString) > 0 THEN
    WHILE(inti <= LENGTH(tempString)) DO
        SET sCurrentChar = SUBSTRING(tempString, inti, 1);
        IF inti > 1 THEN
           SET sPreviousChar = SUBSTRING(tempString, inti - 1, 1);
            IF sCurrentChar = sPreviousChar THEN
                SET tempString = CONCAT(LEFT(tempString, inti - 1), SUBSTRING(tempString, inti, 1000));
            END IF;
        END IF;
        SET inti = inti + 1;
    END WHILE;
    RETURN (tempString);
ELSE
    RETURN 0;
END IF;    
END
dy2hfwbg

dy2hfwbg1#

CREATE FUNCTION `REMOVE_DUPLICATE_CHAR_FROM_STRING` (`aString` VARCHAR(50) )
RETURNS VARCHAR(50) CHARSET utf8
BEGIN
    DECLARE result VARCHAR(50) DEFAULT '';
    DECLARE prev CHAR(1) DEFAULT '';
    DECLARE c CHAR(1) DEFAULT '';
    DECLARE i TINYINT DEFAULT 1;
    DECLARE len TINYINT;

    SET len = LENGTH(aString);
    WHILE(i <= len) DO
        SET c = SUBSTRING(aString, i, 1);
        IF c != prev THEN
            SET result = CONCAT(result, c);
            SET prev = c;
        END IF;
        SET i = i + 1;
    END WHILE;
    RETURN result;
END

相关问题