ID:195084
 
//Title: Substring Matching and Symbol Counts
//Credit to: Jtgibson
//Contributed by: Jtgibson


/*
These are some utility functions that I wrote for my MediaWiki-style parser,
and I started finding little uses for them all over my code, particularly
for my command line parser.

Since I find them quite generically useful, maybe you might too.
*/




//Return 1 if the text string 'line' starts/ends with the text string
// 'substring' and only the substring. Return 0 if the line starts/ends
// with anything else. The substring must match exactly.
//E.g., line_starts_with("Hello world","Hello") returns 1, while
// line_ends_with("Hello world","World") returns 0.
proc/line_starts_with(line, substring)
if(length(substring) > length(line) || !length(substring)) return 0
else if(copytext(line, 1, 1+length(substring)) == substring) return 1
return 0
proc/line_ends_with(line, substring)
if(length(substring) > length(line) || !length(substring)) return 0
else if(copytext(line, length(line)+1-length(substring)) == substring)
return 1
return 0


//Count the number of occurrences of the string 'symbol' that appear at
// the start of the string 'line'. For instance,
// count_initial_symbols("//Hello","/") will yield 2.
proc/count_initial_symbols(line, symbol)
if(!length(symbol) || !length(line)) return 0
for(var/i = 1, i <= length(line)+1-length(symbol), i += length(symbol))
if(copytext(line,i,i+length(symbol)) == symbol) ++.
else break
proc/count_final_symbols(line, symbol)
if(!length(symbol) || !length(line)) return 0
for(var/i = length(line)+1-length(symbol), i > 0, i -= length(symbol))
if(copytext(line,i,i+length(symbol)) == symbol) ++.
else break


///*
//Testing code/sample implementation:

mob/verb/test_symbolcount()
if(line_starts_with("==Test Section==", "="))
src << "line_starts_with test succeeded"
else
CRASH("line_starts_with test failed")

if(line_ends_with("==Test Section==", "="))
src << "line_ends_with test succeeded"
else
CRASH("line_ends_with test failed")

if(count_initial_symbols("==Test Section==", "=") == 2)
src << "count_initial_symbols test succeeded"
else
CRASH("count_initial_symbols test failed (should be 2, reported \
[count_final_symbols("==Test Section==", "=")]")

if(count_final_symbols("==Test Section==", "=") == 2)
src << "count_final_symbols test succeeded"
else
CRASH("count_final_symbols test failed (should be 2, reported \
[count_final_symbols("==Test Section==", "=")]")

//*/