フィルターのクリア

Cell array, string concatenation

2 ビュー (過去 30 日間)
Danny C
Danny C 2016 年 9 月 7 日
コメント済み: Danny C 2016 年 9 月 7 日
*I'm trying to create a function that will concatenate the two input strings. If one of the strings is longer than the other, I should only concatenate the last N characters of the longer string, where N is the length of the shorter string. For example, if the input strings were 'Hello' and 'MATLAB' the output would be ' HelloATLAB'. 'Hello' is the shorter of the two words at 5 characters, so the last 5 characters of the other string are concatenated. The first input will always be concatenated in front of the second input.
So here's the start that I wrote.
function [str] = shortCat(in1, in2)
cin = {in1; in2};
Lin = [length(in1) length(in2)];
Ldif = abs(Lin(1)-Lin(2));
[~,Lmax] = max(Lin);
I'm lost after this. Can someone help me to solve this?

採用された回答

Mischa Kim
Mischa Kim 2016 年 9 月 7 日
Danny, I would simply use an if-else for that, combined with indexing
function [str] = shortCat(in1, in2)
s1 = size(in1,2);
s2 = size(in2,2);
if s1 > s2
str = [in1(s1-s2+1:s1), in2];
else
str = [in1, in2(s2-s1+1:s2)];
end
end
  1 件のコメント
Danny C
Danny C 2016 年 9 月 7 日
That's so much simpler than the way I was thinking. I should've used if-else loop from the start. Thank you so much!

サインインしてコメントする。

その他の回答 (1 件)

Nobel Mondal
Nobel Mondal 2016 年 9 月 7 日
編集済み: Nobel Mondal 2016 年 9 月 7 日
function outString = myStringConcatenator(inString1, inString2)
minLength = min(length(inString1), length(inString2));
outString = [inString1(length(inString1)-minLength+1 : end) ...
inString2(length(inString2)-minLength+1 : end)];
end

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by