Environment: MySQL 5.5
Requirement: Capitalize the first letter of each word or phrase after separating the string "apple,orange,water melon,banana" with ","
Implementation: Write a function:
drop function if exists fun_initial_upper; delimiter $$ create function fun_initial_upper(sourceStr varchar(255),delim varchar(10)) returns varchar(255) begin declare destinationStr varchar(255) default ''; #return result string declare size integer default 0; #The number of words or phrases obtained with delim as the separator +1 declare tmpStr varchar(255); #Intermediate variable declare len integer default 0; #the length of the word or phrase declare changeDelim bool default false; #Whether to change the delimiter (for input spaces) if delim = '' || delim regexp '[[:blank:]]' then #regular matching whether the delimiter is a space character set sourceStr = replace(sourceStr,delim,'//,'); set delim = '//,'; #custom delimiter set changeDelim = true; end if; set sourceStr = concat(delim,sourceStr); #initialize the source string set size = length(sourceStr)-length(replace(sourceStr,delim,''))+1; loop_label: loop if size > 0 then set tmpStr = substring_index(sourceStr,delim,size-1); set len = char_length(substring_index(sourceStr,delim,size)) - char_length(tmpStr)-char_length(delim); if len > 0 then set tmpStr = trim(substring(sourceStr,char_length(tmpStr)+char_length(delim)+1,len)); set tmpStr = concat(upper(left(tmpStr,1)),substring(tmpStr,2,(length(tmpStr)-1))); set destinationStr = concat(delim,tmpStr,destinationStr); end if; set size = size - 1; else leave loop_label; end if; end loop; set destinationStr = concat(substring(destinationStr,char_length(delim)+1,(length(destinationStr)-1)));#Remove the delim at the beginning, as opposed to set sourceStr = concat(delim,sourceStr) if changeDelim then set destinationStr = replace(destinationStr,delim,' '); end if; return destinationStr; end $$ delimiter ;
function:
- regexp: regular match
- concat(str1,str2,...): String concatenation (concatenate strings str1, str2,...)
- length(str): the length of the string str
- replace(str, from_str, to_str): string replacement (all from_str in string str are replaced by to_str)
- substring_index(str, delim, count): Returns the substring from the string str before the delimiters delim and count appear. If count is a positive value, everything to the left of the final delimiter (starting from the left) is returned. If count is negative, everything to the right of the delimiter (starting from the right) is returned.
- char_length(str): Returns the character length of the string str
- trim(str): remove nulls from the beginning and end of the string
- upper(str): Convert each character of the string to uppercase
- substring(str, pos, len): substring (get the substring of string str with pos as the starting position and length of len)
result: