Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to make substrings and int of a string?

Status
Not open for further replies.

abmargb

Programmer
Oct 3, 2005
2
0
0
BR
Hi people!
I have a string oneword...
It has the following model:
16c#2
8a3
4d#1
As you can see, it is similar to Nokia RingTone system...
However...
I need to separate this string into three pieces:

int dura: the first integer part, that means the duration, 16 in the first example;
char note: the character part, that means the note, 'c#' in the first example;
int oct: the last integer part, which means the octave, 2 in the first example.

How can I do this?
I am newbie in C programming, nad I'm doing a program that uses the PC speaker to read and play the NoKia Ringtones..

Thanks in advance.
 
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct
{
  int dura;
  char note[8]; /* 8... Why not?.. */
  int  oct;
} Note;

static const char Digits[] = "0123456789";

/* Returns 3 (all parts presen) if OK. */
int	ParseNote(Note* p, const char* str)
{
  int	k, n, rc = 0;
  const char* q;
  Note  junk;

  if (!str || !str) /* Bad arg */
     return 0;
  if (!p)
     p = &junk; /* Check only */
  if ((p->dura = atoi(str)) <= 0) /* No duration */
     return 0;
  rc = 1;
  n = strspn(str,Digits);
  if (n == 0)
     return 1; /* No note */
  q = str + n;

  k = strcspn(q,Digits);
  if (k > 0)
  {
     p->oct = atoi(q+k);
     if (k >= sizeof(p->note)) /* Buffer overflow? */
        k = sizeof(p->note)-1;
     memcpy(p->note,q,k);
     p->note[k] = 0; /* Make C string */
     rc = 2; /* Have a dur+note */
  }
  else /* No note */
  {
     p->oct = 0;
     p->note[0] = 0;
  }
  if (p->oct) /* All parts present */
     rc = 3;
  return rc;
}

void PrintNote(const Note* p)
{
  if (p)
  {
     printf("%d%.8s%d\n",p->dura,p->note,p->oct);
  }
}
 
Thanks so musch!!!
It worked perfectly!!

[]s
 
Sorry, I don't get this...

Code:
if (!str || !str) /* Bad arg */
     return 0;

Why do you say (!str || !str) instead of just (!str) ?

Cheers,

-- Joe
 
i think that should be
(!str || !*str)

first you check the pointer isnt null then you check the strings first byte isnt 0.
 
Yes, of course:
Code:
(!str || !*str)
Sorry.
Thank you, CodingNovice.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top