• C

C Programing - get substring between two chars

I have  strings like follow.

 char str1[]="455:2355;";
 char str2[]="317:5569;";
 char str2[]="213:8254;";

What is the easiest way to get the integer value between ":" and ";"?
I could get the first one (i.e. 455,317,213 ...) using atoi(str1).
I'm using gcc version 3.3.2

Who is Participating?
Infinity08Connect With a Mentor Commented:
Or you can use strtol to retrieve both values :
char str1[] = "455:2355;";
char *pos = 0;
long value = 0;
long value2 = 0;
value = strtol(str1, &pos, 10);
/* pos now points to the ':' character - you can check this to make sure */
value2 = strtol(pos + 1, &pos, 10);
/* pos now points to the ';' character - you can check this to make sure */

Open in new window

If the format of your strings will always be like that, then something like this should work :
char str1[] = "455:2355;";
int value = 0;
char *pos = strstr(str1, ':');
if (pos) {
  value = atoi(pos + 1);

Open in new window

Or you can use strtok to tokenize the string, and then use atoi to convert each token to its corresponding integer value.
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

char str1[] = "455:2355;";

string result=str1.substring(str1,str1.charat(':') , str1.charat(';') - str1.charat(':') );
convert result to integer

@divyeshhdoshi : this is about C ;)
shanikawmAuthor Commented:
Great. Thanks.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.