SORU
23 EYLÜL 2008, Salı


Nasıl standart bir şekilde lider/sondaki boşlukları kırpmak mı?

Lider süsleme ve C bir dize gelen ve sondaki boşluk temiz, tercihen standart bir yöntem var mı? Benim kendi rulo isterdim ama bu eşit ortak bir çözüm ile ortak bir sorun olduğunu düşünürdüm.

CEVAP
23 EYLÜL 2008, Salı


Dize değiştirebilirsiniz:

// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated.  The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str  ;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str   strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end 1) = 0;

  return str;
}

Eğer dize değiştirebilirsiniz eğer doğru değilse, o zaman temelde aynı yöntemi kullanabilirsiniz:

// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result.  If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
  if(len == 0)
    return 0;

  const char *end;
  size_t out_size;

  // Trim leading space
  while(isspace(*str)) str  ;

  if(*str == 0)  // All spaces?
  {
    *out = 0;
    return 1;
  }

  // Trim trailing space
  end = str   strlen(str) - 1;
  while(end > str && isspace(*end)) end--;
  end  ;

  // Set output size to minimum of trimmed string length and buffer size minus 1
  out_size = (end - str) < len-1 ? (end - str) : len-1;

  // Copy trimmed string and add null terminator
  memcpy(out, str, out_size);
  out[out_size] = 0;

  return out_size;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Ricardo Cerqueira

    Ricardo Cerq

    28 Mayıs 2008
  • SRT Photoshop Tutorials

    SRT Photosho

    19 Aralık 2012
  • xXGAMERrs_Xx

    xXGAMERrs_Xx

    31 Temmuz 2014