Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,


I wrote below logic to find substring position in string but my logic is failed.If sub-string is there more then one place.


Objective-C
#include "stdafx.h"
#include<stdio.h>
#include<string.h>
#include<iostream.h>

int compareposition(char* str1,char str2);
int main()
{
    char SensexGraphUrl[100];
	memset(SensexGraphUrl,0,100);
	int i,j;
	char* strarray="SENSEXGRAPHURL";
	char* str1= "SE";
    int count=0;
	int iLen = strlen(strarray);
	int iLen1 = strlen(str1) ;

	int pos=0;

	for(i=0;i<iLen1;i++)
	{
		pos = compareposition(strarray,str1[i]);
		cout<<"Pos"<<pos <<endl;
		//strncpy((char*)strarray[pos],"",1);
			
		if(iLen1 == 2)
		{
		
		pos = compareposition(strarray,str1[i]);
		cout<<"Pos"<<pos <<endl;
		}
	}
return 0;
}


int compareposition(char* str1,char str2)
{

	int j;

	int istrlen = strlen(str1); 
    
	for(j=0;j<istrlen;j++)
	{
		if(str1[j] == str2)
			return j;
		else
			continue;

	}


	return 0;
}


.
Posted
Comments
CPallini 13-May-14 8:04am    
Isn't strlen a stadard API function?
ranjithkumar81 15-May-14 5:15am    
int iLenCount=0;

while(*strarray)
{
iLenCount++;
*strarray++;

}

iLenCount=14

for(i=0;i<ilen1;i++)>
{
  pos = compareposition(strarray,str1[i]);


should crash if i is 4 because str1 has only two chars and a terminating zero.

use a debugger as all programmers do ;-)
 
Share this answer
 
Comments
Rage 13-May-14 7:46am    
Why should i be 4 ?
KarstenK 15-May-14 4:19am    
char* str1= "SE";

2 valid chars and a separator are 3. It crashes the next round.
Rage 15-May-14 8:14am    
iLen1=strlen(str1). How could the for loop not escape ???
There is a flaw in your logic:
The first for should loop on the searched string "SENSE...", not on the search string "SE". Then, do a one to one comparison for all following caracters, and interrupt if no match.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900