Issue
I need to find the largest common prefix of two strings using CMake. I did not yet find anything about it using CMake. CMake itself is quite limited so I wonder about the best approach.
Solution
Finding the largest common prefix is usually done in an O(n) linear search beginning at the start of both strings. CMake allows comparing numbers and strings using the if command and LESS/GREATER/.. . This allows to implement the standard way of finding the largest common prefix:
function( largest_common_prefix a b prefix )
# minimum of lengths of both strings
string( LENGTH ${a} len_a )
string( LENGTH ${b} len_b )
if( ${len_a} LESS ${len_b} )
set( len ${len_a} )
else()
set( len ${len_b} )
endif()
# iterate over the length
foreach( end RANGE 1 ${len} )
# get substrings
string( SUBSTRING ${a} 0 ${end} sub_a )
string( SUBSTRING ${b} 0 ${end} sub_b )
# if equal store, otherwise break
if ( ${sub_a} STREQUAL ${sub_b} )
set( ${prefix} ${sub_a} PARENT_SCOPE )
else()
break()
endif()
endforeach()
endfunction()
Answered By - NoDataDumpNoContribution Answer Checked By - David Goodson (WPSolving Volunteer)