Swap first and last word in a string

조회 수: 13 (최근 30일)
Nobita Nobi
Nobita Nobi 2019년 5월 18일
편집: madhan ravi 2019년 5월 18일
Hi there,
Can anyone please tell me how to continue this task? I am able to find the first and last word but could not figure out the way to swap them.
Many thanks!
function f = swap(str)
s=' ';
sp=strfind(str,s);
for i=1:sp(1)-1
firstword(i)=str(i);
end
lastword = str(sp(end)+1:end);

채택된 답변

madhan ravi
madhan ravi 2019년 5월 18일
편집: madhan ravi 2019년 5월 18일
Simpler:
s = 'hello world';
Wanted = swap(s) % function call
% function
function Wanted = swap(str)
S = regexp(str,'\S*','match');
S([1,end]) = S([end,1]);
Wanted = strjoin(S);
end

추가 답변 (1개)

Image Analyst
Image Analyst 2019년 5월 18일
Here's one way:
% Create sample string.
str = 'one two three four five';
% Split apart into individual words without spaces.
words = strsplit(str)
% Swap the first and last words.
[words(end), words(1)] = deal(words(1), words(end))
% String the words together with spaces between them.
outputString = ''; % Initialize output
for k = 1 : length(words)
outputString = sprintf('%s ', outputString, words{k});
end
% Trim off the leading and trailing spaces.
outputString = strtrim(outputString)
  댓글 수: 1
madhan ravi
madhan ravi 2019년 5월 18일
편집: madhan ravi 2019년 5월 18일
This adds an extra space inbetween words.
>> strlength(str)
ans =
23
>> strlength(outputString)
ans =
27
>>

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by