please anyone convert this c++ code into MATLAB

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,cnt,l,count[50];
char str[50];
clrscr();
printf("Enter the string");
scanf("%s",str);
printf("\n\t original s]==string is:%s",str);
printf("\n\n\t encoded string is:");
for(i=0;i<l;i=i*1)
{
j=0;
count[i]=1;
do
{
j++;
if(str[i+j]==str[i])
count[i]++;
}
while(str[i+j]==str[i]);
if(count[i]==1)
printf("%c",str[i++]);
else
{
printf("%c%d",str[i],count[i]);
i=i+count[i];
}
}
getch();
}

2 Kommentare

for(i=0;i<l;i=i*1)
In the above line, you use variable l before it is defined. Is l supposed to be the length of the string str?
Also, the last part of this for construct is i=i*1, which will essentially do nothing. Is this intended? If you want to do nothing here, then typically one would leave that part blank rather than put in code that accomplishes nothing.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

James Tursa
James Tursa am 25 Mär. 2015
Bearbeitet: James Tursa am 25 Mär. 2015

0 Stimmen

Making assumption that l is the string length (a really BAD choice for a variable name btw), here is a fairly literal translation. The functionality appears to simply count repeated letters and put that count into the output string, so this whole thing could probably be rewritten using that knowledge (but I am not going to do that for you here).
function estring(str)
l = numel(str);
i = 0;
count = zeros(1,l);
while( i < l )
j=0;
count(i+1) = 1;
while( true )
j = j + 1;
if( i+j+1 > l )
break;
end
if( str(i+j+1)==str(i+1) )
count(i+1) = count(i+1) + 1;
else
break;
end
end
if( count(i+1)==1 )
fprintf('%c',str(i+1)); i = i + 1;
else
fprintf('%c%d',str(i+1),count(i+1));
i = i + count(i+1);
end
end
fprintf('\n');
end
E.g.,
>> estring('abcdef')
abcdef
>> estring('aabbbcdeeeeef')
a2b3cde5f
>> estring('abcccdefggggggggggggggggggggg')
abc3defg21

Kategorien

Gefragt:

am 25 Mär. 2015

Bearbeitet:

am 25 Mär. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by