필터 지우기
필터 지우기

please anyone convert this c++ code into MATLAB

조회 수: 2 (최근 30일)
tina jain
tina jain 2015년 3월 25일
편집: James Tursa 2015년 3월 25일
#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
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
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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by