Write a function right fills n that fills the string s with

Write a function right fill(s. n) that fills the string s with blanks from the right until its total length is n characters. If s is longer than n characters, it must be truncated

Solution

The solution for this problem is this:

function sn=rightfill(s,n,f)
%s variable string type
%n variable integer type
%f how work the fuction, f=0==> the function delete the last n caracters.
% f=1==> the function fill the last n caracters, but
% the length of the s not change.
%sn new string

if class(s)~=\'char\'
msgbox(\'The variable s must be string type\');
end

if class(n)~=\'double\'& ~isinteger(n)
msgbox(\'The variable n must be double or integer type\');
end

if nargin==2
f=1;
end

if f==0
if n>=length(s)
sp=[];%string partial
else
sp=s;
sp(end-n+1:end)=[];%string partial
end
elseif f==1
if n>=length(s)
for i=1:length(s)
sp(i)=\' \';%string partial
end
else
sp=s;
for i=1:n
sp(end-i+1)=\' \';%string partial
end
end
end
sn=sp;

In the code we take the values of the s and n variable and if nis greater than s, fill with \' \' all the spaces of s, but if n<s we must fill with \' \' each position in the s string vector and we cut the string from the right to left.

Regards,

 Write a function right fill(s. n) that fills the string s with blanks from the right until its total length is n characters. If s is longer than n characters,

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site