please anyone convert this c++ code into MATLAB
1 回表示 (過去 30 日間)
古いコメントを表示
#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 件のコメント
James Tursa
2015 年 3 月 25 日
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.
回答 (1 件)
James Tursa
2015 年 3 月 25 日
編集済み: James Tursa
2015 年 3 月 25 日
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!