MATLAB: How to find a common part of the strings

Hi there!
Could you please help me how to find a common part of the strings?
for example: S1_carbon_avg_air, S1_carbon_err_air, S1_carbon_avg_arg, S1_carbon_err_arg, S1_carbon_avg_nit, S1_carbon_err_nit,
the coomon string is S1_carbon and i want to use this as legend and title of the graph as well.
Thank you in advance
Abdul kalam

Best Answer

If you have the strings in a cell array of strings, Scell, then
Schar = char(Scell(:));
all_rows_same = all(diff(Schar == 0, 1),1);
common_cols = find(~all_rows_same, 1, 'first');
if isempty(common_cols)
common_to_use = '?'
else
common_to_use = Scell{1}(1:common_cols);
end
This finds the longest leading substring common to all entries in the cell array and uses that; however if there is no leading substring that is common to all of them then it uses '?' just to have something .