Jak przycinać początkowe / końcowe białe znaki w standardowy sposób?

Czy istnieje czysta, najlepiej standardowa metoda przycinania początkowych i końcowych białych spacji z ciągu znaków w C? Sam bym to zrobił, ale uważam, że jest to powszechny problem z równie powszechnym rozwiązaniem.

Author: Stephen, 2008-09-23

30 answers

Jeśli możesz zmodyfikować ciąg znaków:

// 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((unsigned char)*str)) str++;

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

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

  // Write new null terminator character
  end[1] = '\0';

  return str;
}

Jeśli nie możesz zmodyfikować ciągu, możesz użyć zasadniczo tej samej metody:

// 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((unsigned char)*str)) str++;

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

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*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;
}
 139
Author: Adam Rosenfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-14 08:20:03

Oto jeden, który przesuwa łańcuch na pierwszą pozycję Twojego bufora. Możesz chcieć tego zachowania, aby jeśli dynamicznie przydzielono ciąg znaków, nadal można go zwolnić na tym samym wskaźniku, który zwraca trim ():

char *trim(char *str)
{
    size_t len = 0;
    char *frontp = str;
    char *endp = NULL;

    if( str == NULL ) { return NULL; }
    if( str[0] == '\0' ) { return str; }

    len = strlen(str);
    endp = str + len;

    /* Move the front and back pointers to address the first non-whitespace
     * characters from each end.
     */
    while( isspace((unsigned char) *frontp) ) { ++frontp; }
    if( endp != frontp )
    {
        while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}
    }

    if( str + len - 1 != endp )
            *(endp + 1) = '\0';
    else if( frontp != str &&  endp == frontp )
            *str = '\0';

    /* Shift the string so that it starts at str so that if it's dynamically
     * allocated, we can still free it on the returned pointer.  Note the reuse
     * of endp to mean the front of the string buffer now.
     */
    endp = str;
    if( frontp != str )
    {
            while( *frontp ) { *endp++ = *frontp++; }
            *endp = '\0';
    }


    return str;
}

Test poprawności:

int main(int argc, char *argv[])
{
    char *sample_strings[] =
    {
            "nothing to trim",
            "    trim the front",
            "trim the back     ",
            " trim one char front and back ",
            " trim one char front",
            "trim one char back ",
            "                   ",
            " ",
            "a",
            "",
            NULL
    };
    char test_buffer[64];
    int index;

    for( index = 0; sample_strings[index] != NULL; ++index )
    {
            strcpy( test_buffer, sample_strings[index] );
            printf("[%s] -> [%s]\n", sample_strings[index],
                                     trim(test_buffer));
    }

    /* The test prints the following:
    [nothing to trim] -> [nothing to trim]
    [    trim the front] -> [trim the front]
    [trim the back     ] -> [trim the back]
    [ trim one char front and back ] -> [trim one char front and back]
    [ trim one char front] -> [trim one char front]
    [trim one char back ] -> [trim one char back]
    [                   ] -> []
    [ ] -> []
    [a] -> [a]
    [] -> []
    */

    return 0;
}

Plik źródłowy został przycięty.C. skompilowane z ' CC trim.C-O trim".

 29
Author: indiv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-19 18:57:06

Moje rozwiązanie. Ciąg musi być zmienny. Przewaga nad niektórymi innymi rozwiązaniami polega na tym, że przesuwa część nie-spacji na początek, więc możesz nadal używać starego wskaźnika, na wypadek, gdybyś musiał go później uwolnić.

void trim(char * s) {
    char * p = s;
    int l = strlen(p);

    while(isspace(p[l - 1])) p[--l] = 0;
    while(* p && isspace(* p)) ++p, --l;

    memmove(s, p, l + 1);
}   

Ta wersja tworzy kopię łańcucha za pomocą strndup() zamiast edytować go w miejscu. strndup () wymaga _GNU_SOURCE, więc być może musisz utworzyć własną strndup () za pomocą malloc () i strncpy ().

char * trim(char * s) {
    int l = strlen(s);

    while(isspace(s[l - 1])) --l;
    while(* s && isspace(* s)) ++s, --l;

    return strndup(s, l);
}
 18
Author: jkramer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-23 20:47:23

Oto moja Mini biblioteka C do przycinania lewej, prawej, obu, wszystkich, na miejscu i osobno, oraz przycinania zestawu określonych znaków (lub domyślnie białych spacji).

Zawartość strlib.h:

#ifndef STRLIB_H_
#define STRLIB_H_ 1
enum strtrim_mode_t {
    STRLIB_MODE_ALL       = 0, 
    STRLIB_MODE_RIGHT     = 0x01, 
    STRLIB_MODE_LEFT      = 0x02, 
    STRLIB_MODE_BOTH      = 0x03
};

char *strcpytrim(char *d, // destination
                 char *s, // source
                 int mode,
                 char *delim
                 );

char *strtriml(char *d, char *s);
char *strtrimr(char *d, char *s);
char *strtrim(char *d, char *s); 
char *strkill(char *d, char *s);

char *triml(char *s);
char *trimr(char *s);
char *trim(char *s);
char *kill(char *s);
#endif

Zawartość strlib.c:

#include <strlib.h>

char *strcpytrim(char *d, // destination
                 char *s, // source
                 int mode,
                 char *delim
                 ) {
    char *o = d; // save orig
    char *e = 0; // end space ptr.
    char dtab[256] = {0};
    if (!s || !d) return 0;

    if (!delim) delim = " \t\n\f";
    while (*delim) 
        dtab[*delim++] = 1;

    while ( (*d = *s++) != 0 ) { 
        if (!dtab[0xFF & (unsigned int)*d]) { // Not a match char
            e = 0;       // Reset end pointer
        } else {
            if (!e) e = d;  // Found first match.

            if ( mode == STRLIB_MODE_ALL || ((mode != STRLIB_MODE_RIGHT) && (d == o)) ) 
                continue;
        }
        d++;
    }
    if (mode != STRLIB_MODE_LEFT && e) { // for everything but trim_left, delete trailing matches.
        *e = 0;
    }
    return o;
}

// perhaps these could be inlined in strlib.h
char *strtriml(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_LEFT, 0); }
char *strtrimr(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_RIGHT, 0); }
char *strtrim(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_BOTH, 0); }
char *strkill(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_ALL, 0); }

char *triml(char *s) { return strcpytrim(s, s, STRLIB_MODE_LEFT, 0); }
char *trimr(char *s) { return strcpytrim(s, s, STRLIB_MODE_RIGHT, 0); }
char *trim(char *s) { return strcpytrim(s, s, STRLIB_MODE_BOTH, 0); }
char *kill(char *s) { return strcpytrim(s, s, STRLIB_MODE_ALL, 0); }

Jedna główna rutyna robi wszystko. It trims in place if src == dst , inaczej, to działa jak strcpy procedury. Przycina zbiór znaków określonych w łańcuchu delim , lub białą spacją, jeśli null. Przycina lewo, prawo, oba i wszystkie (jak tr). Nie ma w tym zbyt wiele, a iteracje nad ciągiem tylko raz. Niektórzy ludzie mogą narzekać, że trim right zaczyna się po lewej stronie, jednak nie jest potrzebny strlen, który i tak zaczyna się po lewej stronie. (W ten czy inny sposób musisz dotrzeć do końca sznurka, aby uzyskać odpowiednie wykończenia, więc równie dobrze możesz wykonywać pracę, jak idziesz.) Mogą być argumenty na temat wielkości pipeliningu i cache i takie -- kto wie. Ponieważ rozwiązanie działa od lewej do prawo i powtarza się tylko raz, może być rozszerzony do pracy na strumieniach, jak również. Ograniczenia: nie działa na łańcuchachunicode .

 8
Author: Shoots the Moon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-03 21:20:33

Oto moja próba prostej, ale poprawnej funkcji trymowania w miejscu.

void trim(char *str)
{
    int i;
    int begin = 0;
    int end = strlen(str) - 1;

    while (isspace((unsigned char) str[begin]))
        begin++;

    while ((end >= begin) && isspace((unsigned char) str[end]))
        end--;

    // Shift all characters back to the start of the string array.
    for (i = begin; i <= end; i++)
        str[i - begin] = str[i];

    str[i - begin] = '\0'; // Null terminate string.
}
 7
Author: Swiss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 20:45:22

Oto rozwiązanie podobne do @ adam-rosenfields in-place modification, ale bez niepotrzebnego uciekania się do strlen (). Podobnie jak @jkramer, łańcuch jest ustawiany w lewo w buforze, dzięki czemu można zwolnić ten sam wskaźnik. Nie jest optymalny dla dużych strun, ponieważ nie używa memmove. Zawiera operatory++/--, o których wspomina @jfm3. fctx -włączone testy jednostkowe.

#include <ctype.h>

void trim(char * const a)
{
    char *p = a, *q = a;
    while (isspace(*q))            ++q;
    while (*q)                     *p++ = *q++;
    *p = '\0';
    while (p > a && isspace(*--p)) *p = '\0';
}

/* See http://fctx.wildbearsoftware.com/ */
#include "fct.h"

FCT_BGN()
{
    FCT_QTEST_BGN(trim)
    {
        { char s[] = "";      trim(s); fct_chk_eq_str("",    s); } // Trivial
        { char s[] = "   ";   trim(s); fct_chk_eq_str("",    s); } // Trivial
        { char s[] = "\t";    trim(s); fct_chk_eq_str("",    s); } // Trivial
        { char s[] = "a";     trim(s); fct_chk_eq_str("a",   s); } // NOP
        { char s[] = "abc";   trim(s); fct_chk_eq_str("abc", s); } // NOP
        { char s[] = "  a";   trim(s); fct_chk_eq_str("a",   s); } // Leading
        { char s[] = "  a c"; trim(s); fct_chk_eq_str("a c", s); } // Leading
        { char s[] = "a  ";   trim(s); fct_chk_eq_str("a",   s); } // Trailing
        { char s[] = "a c  "; trim(s); fct_chk_eq_str("a c", s); } // Trailing
        { char s[] = " a ";   trim(s); fct_chk_eq_str("a",   s); } // Both
        { char s[] = " a c "; trim(s); fct_chk_eq_str("a c", s); } // Both

        // Villemoes pointed out an edge case that corrupted memory.  Thank you.
        // http://stackoverflow.com/questions/122616/#comment23332594_4505533
        {
          char s[] = "a     ";       // Buffer with whitespace before s + 2
          trim(s + 2);               // Trim "    " containing only whitespace
          fct_chk_eq_str("", s + 2); // Ensure correct result from the trim
          fct_chk_eq_str("a ", s);   // Ensure preceding buffer not mutated
        }

        // doukremt suggested I investigate this test case but
        // did not indicate the specific behavior that was objectionable.
        // http://stackoverflow.com/posts/comments/33571430
        {
          char s[] = "         foobar";  // Shifted across whitespace
          trim(s);                       // Trim
          fct_chk_eq_str("foobar", s);   // Leading string is correct

          // Here is what the algorithm produces:
          char r[16] = { 'f', 'o', 'o', 'b', 'a', 'r', '\0', ' ',                     
                         ' ', 'f', 'o', 'o', 'b', 'a', 'r', '\0'};
          fct_chk_eq_int(0, memcmp(s, r, sizeof(s)));
        }
    }
    FCT_QTEST_END();
}
FCT_END();
 3
Author: Rhys Ulerich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-02 15:40:36

Kolejny, z jednym wierszem wykonującym prawdziwą pracę:

#include <stdio.h>

int main()
{
   const char *target = "   haha   ";
   char buf[256];
   sscanf(target, "%s", buf); // Trimming on both sides occurs here
   printf("<%s>\n", buf);
}
 3
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-11 17:16:13

Spóźnienie na imprezę

Cechy:
1. Przyciąć początek szybko, jak w wielu innych odpowiedziach.
2. Po przejściu do końca, przycinanie w prawo tylko 1 test na pętlę. Podobnie jak @jfm3, ale działa na cały biały ciąg znaków)
3. Aby uniknąć niezdefiniowanego zachowania, gdy char jest znakiem char, należy przerzucić *s na unsigned char.

Obsługa znaków " we wszystkich przypadkach argumentem jest int, którego wartość jest reprezentowalna jako unsigned char lub jest równa wartości makra EOF. Jeśli argument ma inną wartość, zachowanie jest niezdefiniowane."C11 §7.4 1

#include <ctype.h>

// Return a pointer to the trimmed string
char *string_trim_inplace(char *s) {
  while (isspace((unsigned char) *s)) s++;
  if (*s) {
    char *p = s;
    while (*p) p++;
    while (isspace((unsigned char) *(--p)));
    p[1] = '\0';
  }
  return s;
}
 3
Author: chux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-17 23:38:52

Nie podobała mi się większość z tych odpowiedzi, ponieważ wykonali jedną lub więcej z następujących czynności...

  1. zwrócił inny wskaźnik wewnątrz ciągu oryginalnego wskaźnika (rodzaj bólu, aby żonglować dwoma różnymi wskaźnikami do tej samej rzeczy).
  2. bezinteresowne użycie takich rzeczy jak strlen () , które wstępnie iterują cały łańcuch.
  3. używane nie Przenośne funkcje lib specyficzne dla systemu operacyjnego.
  4. Backscaned.
  5. użyte porównanie do ' ' zamiast isspace () więc ta karta / CR / LF jest zachowana.
  6. zmarnowana pamięć z dużymi buforami statycznymi.
  7. zmarnowane cykle z wysokobudżetowymi funkcjami, takimi jak sscanf / sprintf .

Oto moja wersja:

void fnStrTrimInPlace(char *szWrite) {

    const char *szWriteOrig = szWrite;
    char       *szLastSpace = szWrite, *szRead = szWrite;
    int        bNotSpace;

    // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST
    while( *szRead != '\0' ) {

        bNotSpace = !isspace((unsigned char)(*szRead));

        if( (szWrite != szWriteOrig) || bNotSpace ) {

            *szWrite = *szRead;
            szWrite++;

            // TRACK POINTER TO LAST NON-SPACE
            if( bNotSpace )
                szLastSpace = szWrite;
        }

        szRead++;
    }

    // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)
    *szLastSpace = '\0';
}
 3
Author: Jason Stewart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-18 23:38:57

Najprostszym sposobem na pominięcie spacji w łańcuchu jest, imho,

#include <stdio.h>

int main()
{
char *foo="     teststring      ";
char *bar;
sscanf(foo,"%s",bar);
printf("String is >%s<\n",bar);
    return 0;
}
 2
Author: Zibri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 13:22:43

bardzo późno na przyjęcie...

Jednoprzebiegowe rozwiązanie do skanowania do przodu bez cofania. Każdy znak w łańcuchu źródłowym jest testowany dokładnie raz. (Więc powinno być szybsze niż większość innych rozwiązań tutaj, zwłaszcza jeśli łańcuch źródłowy ma wiele spacji końcowych.)

Obejmuje to dwa rozwiązania, jedno do kopiowania i przycinania łańcucha źródłowego do innego łańcucha docelowego, a drugie do przycinania łańcucha źródłowego w miejscu. Obie funkcje używają tego samego kod.

(modyfikowalny) łańcuch jest przenoszony na miejsce, więc oryginalny wskaźnik do niego pozostaje niezmieniony.

#include <stddef.h>
#include <ctype.h>

char * trim2(char *d, const char *s)
{
    // Sanity checks
    if (s == NULL  ||  d == NULL)
        return NULL;

    // Skip leading spaces        
    unsigned const char * p = (unsigned const char *)s;
    while (isspace(*p))
        p++;

    // Copy the string
    unsigned char * dst = (unsigned char *)d;   // d and s can be the same
    unsigned char * end = dst;
    while (*p != '\0')
    {
        if (!isspace(*dst++ = *p++))
            end = dst;
    }

    // Truncate trailing spaces
    *end = '\0';
    return d;
}

char * trim(char *s)
{
    return trim2(s, s);
}
 2
Author: David R Tribble,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 19:11:12

Użyj string library , na przykład:

Ustr *s1 = USTR1(\7, " 12345 ");

ustr_sc_trim_cstr(&s1, " ");
assert(ustr_cmp_cstr_eq(s1, "12345"));

... jak mówisz, że jest to" powszechny " problem, tak, musisz dołączyć #include lub tak i nie jest on zawarty w libc, ale nie wymyślaj własnej pracy hakerskiej przechowującej losowe wskaźniki i size_t w ten sposób prowadzi tylko do przepełnienia bufora.

 1
Author: James Antill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-24 04:07:53
#include "stdafx.h"
#include "malloc.h"
#include "string.h"

int main(int argc, char* argv[])
{

  char *ptr = (char*)malloc(sizeof(char)*30);
  strcpy(ptr,"            Hel  lo    wo           rl   d G    eo rocks!!!    by shahil    sucks b i          g       tim           e");

  int i = 0, j = 0;

  while(ptr[j]!='\0')
  {

      if(ptr[j] == ' ' )
      {
          j++;
          ptr[i] = ptr[j];
      }
      else
      {
          i++;
          j++;
          ptr[i] = ptr[j];
      }
  }


  printf("\noutput-%s\n",ptr);
        return 0;
}
 1
Author: Balkrishna Talele,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-14 21:05:07

S był tak bardzo pomocny, chciałem powiedzieć, że cieszę się, że ten post był dostępny i pokazać, co udało mi się zrobić z przykładami. Musiałem tokenizować większy ciąg znaków, a następnie wziąć podłańcuchy i znaleźć ostatni - aby móc usunąć nową linię z wywołania fgets (), a także usunąć białe spacje z przodu tego tokenu-abym mógł łatwo porównać go ze statycznym ciągiem. Pierwszy przykład w powyższym poście mnie tam dopadł, więc dziękuję. Oto jak użyłem próbek kodu i wyjście, które mam.

int _tmain(int argc, _TCHAR* argv[])
{
   FILE * fp;   // test file
   char currDBSStatstr[100] = {"/0"};
   char *beg;
   char *end;
   char *str1;
   char str[] = "Initializing DBS Configuration";
   fp = fopen("file2-1.txt","r");
   if (fp != NULL)
   {
      printf("File exists.\n");
      fgets(currDBSStatstr, sizeof(currDBSStatstr), fp);
   }
   else
   {
      printf("Error.\n");
      exit(2);
   }  
   //print string
   printf("String: %s\n", currDBSStatstr);
   //extract first string
   str1 = strtok(currDBSStatstr, ":-");
   //print first token
   printf("%s\n", str1);
   //get more tokens in sequence
   while(1)
   {
      //extract more tokens in sequence
      str1 = strtok(NULL, ":-");
      //check to see if done
      if (str1 == NULL)
      {
         printf("Tokenizing Done.\n");
         exit(0);
      }
      //print string after tokenizing Done
      printf("%s\n", str1);
      end = str1 + strlen(str1) - 1;
      while((end > str1) && (*end == '\n'))
      {
         end--;
         *(end+1) = 0;
         beg = str1;
         while(isspace(*str1))
            str1++;
      }
      printf("%s\n", str1);
      if (strcmp(str, str1) == 0)
         printf("Strings are equal.\n");
   }
   return 0;

}

Output

Plik istnieje.

String: DBS State: DBS Startup-Inicjalizacja konfiguracji DBS

DBS State

DBS Startup

DBS Startup

Inicjalizacja konfiguracji DBS

Inicjalizacja konfiguracji DBS

Ciągi są równe.

Tokenizacja Zakończona.

 1
Author: Diana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-05 13:33:56

Jeśli używasz glib, możesz użyć g_strstrip

 1
Author: sleepycal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-08 11:00:15

Żeby tak dalej rosło, jeszcze jedna opcja z modyfikowalnym ciągiem:

void trimString(char *string)
{
    size_t i = 0, j = strlen(string);
    while (j > 0 && isspace((unsigned char)string[j - 1])) string[--j] = '\0';
    while (isspace((unsigned char)string[i])) i++;
    if (i > 0) memmove(string, string + i, j - i + 1);
}
 1
Author: wallek876,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-11 06:23:45

Wiem, że odpowiedzi jest wiele, ale zamieszczam tutaj swoją odpowiedź, aby sprawdzić, czy moje rozwiązanie jest wystarczająco dobre.

// Trims leading whitespace chars in left `str`, then copy at almost `n - 1` chars
// into the `out` buffer in which copying might stop when the first '\0' occurs, 
// and finally append '\0' to the position of the last non-trailing whitespace char.
// Reture the length the trimed string which '\0' is not count in like strlen().
size_t trim(char *out, size_t n, const char *str)
{
    // do nothing
    if(n == 0) return 0;    

    // ptr stop at the first non-leading space char
    while(isspace(*str)) str++;    

    if(*str == '\0') {
        out[0] = '\0';
        return 0;
    }    

    size_t i = 0;    

    // copy char to out until '\0' or i == n - 1
    for(i = 0; i < n - 1 && *str != '\0'; i++){
        out[i] = *str++;
    }    

    // deal with the trailing space
    while(isspace(out[--i]));    

    out[++i] = '\0';
    return i;
}
 1
Author: Ekeyme Mo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-09 05:18:58

Osobiście sam bym to zrobił. Możesz użyć strtok, ale musisz zadbać o to (szczególnie jeśli usuwasz wiodące postacie), aby wiedzieć, co to jest pamięć.

Pozbycie się spacji końcowych jest łatwe i całkiem bezpieczne, ponieważ można po prostu umieścić 0 Na górze ostatniej spacji, licząc od końca. Pozbycie się wiodących przestrzeni oznacza przemieszczanie rzeczy. Jeśli chcesz to zrobić na miejscu (chyba rozsądnie) możesz po prostu wszystko cofnąć o jeden charakter, dopóki nie ma miejsca na prowadzenie. Albo, aby być bardziej wydajnym, możesz znaleźć indeks pierwszego znaku nie-spacji i przesunąć wszystko z powrotem o tę liczbę. Możesz też użyć wskaźnika do pierwszego znaku nie-spacji(ale wtedy musisz być ostrożny w taki sam sposób, jak w przypadku strtok).

 0
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-23 18:16:02

Nie wiem, co uważasz za " bezbolesne."

Stringi C są dość bolesne. Możemy znaleźć pierwszą pozycję nie-białych znaków trywialnie:
while (isspace(* p)) p++;

Możemy znaleźć ostatnią pozycję nie-białych znaków z dwoma podobnymi trywialnymi ruchami:

while (* q) q++;
do { q--; } while (isspace(* q));

(oszczędziłem Ci bólu związanego z używaniem operatorów * i ++ w tym samym czasie.)

Pytanie brzmi: co z tym zrobić? Typ danych pod ręką nie jest tak naprawdę dużym, solidnym abstrakcyjnym String, który jest łatwe do przemyślenia, ale zamiast tego prawie nie więcej niż tablica bajtów pamięci. Brak solidnego typu danych uniemożliwia napisanie funkcji, która będzie działać tak samo jak funkcja chomp PHperytonby. Co taka funkcja w C zwróci?
 0
Author: jfm3,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-23 18:39:59

Trochę za późno na mecz, ale wrzucę swoje rutyny do walki. Prawdopodobnie nie są najbardziej bezwzględnie wydajne, ale wierzę, że są poprawne i proste (z rtrim() przesuwaniem koperty złożoności): {]}

#include <ctype.h>
#include <string.h>

/*
    Public domain implementations of in-place string trim functions

    Michael Burr
    [email protected]
    2010
*/

char* ltrim(char* s) 
{
    char* newstart = s;

    while (isspace( *newstart)) {
        ++newstart;
    }

    // newstart points to first non-whitespace char (which might be '\0')
    memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\0' terminator

    return s;
}


char* rtrim( char* s)
{
    char* end = s + strlen( s);

    // find the last non-whitespace character
    while ((end != s) && isspace( *(end-1))) {
            --end;
    }

    // at this point either (end == s) and s is either empty or all whitespace
    //      so it needs to be made empty, or
    //      end points just past the last non-whitespace character (it might point
    //      at the '\0' terminator, in which case there's no problem writing
    //      another there).    
    *end = '\0';

    return s;
}

char*  trim( char* s)
{
    return rtrim( ltrim( s));
}
 0
Author: Michael Burr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-16 06:08:51

Większość odpowiedzi do tej pory zrobić jedną z następujących:

  1. Backtrack na końcu łańcucha (tzn. znajdź koniec łańcucha, a następnie Szukaj wstecz, aż nie zostanie znaleziony znak spacji) lub
  2. wywołaj strlen() pierwszy, wykonując drugie przejście przez cały łańcuch.

Ta wersja wykonuje tylko jedno przejście i nie wycofuje się. Dlatego może działać lepiej niż inne, choć tylko wtedy, gdy jest powszechne, aby mieć setki spacji końcowych (co nie jest niezwykłe, gdy Obsługa wyjścia zapytania SQL.)

static char const WHITESPACE[] = " \t\n\r";

static void get_trim_bounds(char  const *s,
                            char const **firstWord,
                            char const **trailingSpace)
{
    char const *lastWord;
    *firstWord = lastWord = s + strspn(s, WHITESPACE);
    do
    {
        *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE);
        lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE);
    }
    while (*lastWord != '\0');
}

char *copy_trim(char const *s)
{
    char const *firstWord, *trailingSpace;
    char *result;
    size_t newLength;

    get_trim_bounds(s, &firstWord, &trailingSpace);
    newLength = trailingSpace - firstWord;

    result = malloc(newLength + 1);
    memcpy(result, firstWord, newLength);
    result[newLength] = '\0';
    return result;
}

void inplace_trim(char *s)
{
    char const *firstWord, *trailingSpace;
    size_t newLength;

    get_trim_bounds(s, &firstWord, &trailingSpace);
    newLength = trailingSpace - firstWord;

    memmove(s, firstWord, newLength);
    s[newLength] = '\0';
}
 0
Author: finnw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-06 19:34:30

Jest to najkrótsza możliwa implementacja, jaką przychodzi mi do głowy:

static const char *WhiteSpace=" \n\r\t";
char* trim(char *t)
{
    char *e=t+(t!=NULL?strlen(t):0);               // *e initially points to end of string
    if (t==NULL) return;
    do --e; while (strchr(WhiteSpace, *e) && e>=t);  // Find last char that is not \r\n\t
    *(++e)=0;                                      // Null-terminate
    e=t+strspn (t,WhiteSpace);                           // Find first char that is not \t
    return e>t?memmove(t,e,strlen(e)+1):t;                  // memmove string contents and terminator
}
 0
Author: Michał Gawlas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-20 11:33:06

Funkcje te zmodyfikują oryginalny bufor, więc jeśli dynamicznie alokowany, oryginalny wskaźnik można uwolnić.

#include <string.h>

void rstrip(char *string)
{
  int l;
  if (!string)
    return;
  l = strlen(string) - 1;
  while (isspace(string[l]) && l >= 0)
    string[l--] = 0;
}

void lstrip(char *string)
{
  int i, l;
  if (!string)
    return;
  l = strlen(string);
  while (isspace(string[(i = 0)]))
    while(i++ < l)
      string[i-1] = string[i];
}

void strip(char *string)
{
  lstrip(string);
  rstrip(string);
}
 0
Author: Telc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-22 13:49:06

Co sądzisz o użyciu funkcji StrTrim zdefiniowanej w nagłówku Shlwapi.h.? To jest proste, a raczej definiowanie na własną rękę.
Szczegóły można znaleźć na:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb773454 (v=vs.85). aspx

Jeśli masz
char ausCaptain[]="GeorgeBailey ";
StrTrim(ausCaptain," ");
To da ausCaptain jako "GeorgeBailey" NIE "GeorgeBailey ".

 0
Author: Carthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-17 23:41:11

Do przycinania strun z obu stron używam starego ale Goody ;) Może przycinać wszystko, co ma ascii mniej niż spacja, co oznacza, że znaki sterujące również zostaną przycięte !

char *trimAll(char *strData)
{
  unsigned int L = strlen(strData);
  if(L > 0){ L--; }else{ return strData; }
  size_t S = 0, E = L;
  while((!(strData[S] > ' ') || !(strData[E] > ' ')) && (S >= 0) && (S <= L) && (E >= 0) && (E <= L))
  {
    if(strData[S] <= ' '){ S++; }
    if(strData[E] <= ' '){ E--; }
  }
  if(S == 0 && E == L){ return strData; } // Nothing to be done
  if((S >= 0) && (S <= L) && (E >= 0) && (E <= L)){
    L = E - S + 1;
    memmove(strData,&strData[S],L); strData[L] = '\0';
  }else{ strData[0] = '\0'; }
  return strData;
}
 0
Author: Деян Добромиров,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-11 10:39:00

Włączam Kod tylko dlatego, że kod zamieszczony do tej pory wydaje się nieoptymalny (i nie mam jeszcze rep do komentowania.)

void inplace_trim(char* s)
{
    int start, end = strlen(s);
    for (start = 0; isspace(s[start]); ++start) {}
    if (s[start]) {
        while (end > 0 && isspace(s[end-1]))
            --end;
        memmove(s, &s[start], end - start);
    }
    s[end - start] = '\0';
}

char* copy_trim(const char* s)
{
    int start, end;
    for (start = 0; isspace(s[start]); ++start) {}
    for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}
    return strndup(s + start, end - start);
}

strndup() jest rozszerzeniem GNU. Jeśli nie masz go lub czegoś równoważnego, rzuć swój własny. Na przykład:

r = strdup(s + start);
r[end-start] = '\0';
 0
Author: sfink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-30 22:11:58

Tutaj używam dynamicznej alokacji pamięci do przycinania łańcucha wejściowego do funkcji trimStr. Najpierw sprawdzamy, ile niepustych znaków istnieje w ciągu wejściowym. Następnie przydzielamy tablicę znaków o takim rozmiarze i dbamy o znak zakończony znakiem null. Kiedy używamy tej funkcji, musimy uwolnić pamięć wewnątrz głównej funkcji.

#include<stdio.h>
#include<stdlib.h>

char *trimStr(char *str){
char *tmp = str;
printf("input string %s\n",str);
int nc = 0;

while(*tmp!='\0'){
  if (*tmp != ' '){
  nc++;
 }
 tmp++;
}
printf("total nonempty characters are %d\n",nc);
char *trim = NULL;

trim = malloc(sizeof(char)*(nc+1));
if (trim == NULL) return NULL;
tmp = str;
int ne = 0;

while(*tmp!='\0'){
  if (*tmp != ' '){
     trim[ne] = *tmp;
   ne++;
 }
 tmp++;
}
trim[nc] = '\0';

printf("trimmed string is %s\n",trim);

return trim; 
 }


int main(void){

char str[] = " s ta ck ove r fl o w  ";

char *trim = trimStr(str);

if (trim != NULL )free(trim);

return 0;
}
 0
Author: saeed_falahat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 12:56:11

Oto Jak to robię. Przycina łańcuch w miejscu, więc nie martw się o dealokację zwracanego łańcucha lub utratę wskaźnika na przydzielony łańcuch. Może nie jest to najkrótsza możliwa odpowiedź, ale powinna być jasna dla większości czytelników.

#include <ctype.h>
#include <string.h>
void trim_str(char *s)
{
    const size_t s_len = strlen(s);

    int i;
    for (i = 0; i < s_len; i++)
    {
        if (!isspace( (unsigned char) s[i] )) break;
    }

    if (i == s_len)
    {
        // s is an empty string or contains only space characters

        s[0] = '\0';
    }
    else
    {
        // s contains non-space characters

        const char *non_space_beginning = s + i;

        char *non_space_ending = s + s_len - 1;
        while ( isspace( (unsigned char) *non_space_ending ) ) non_space_ending--;

        size_t trimmed_s_len = non_space_ending - non_space_beginning + 1;

        if (s != non_space_beginning)
        {
            // Non-space characters exist in the beginning of s

            memmove(s, non_space_beginning, trimmed_s_len);
        }

        s[trimmed_s_len] = '\0';
    }
}
 0
Author: Isaac To,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-15 19:07:48
char* strtrim(char* const str)
{
    if (str != nullptr)
    {
        char const* begin{ str };
        while (std::isspace(*begin))
        {
            ++begin;
        }

        auto end{ begin };
        auto scout{ begin };
        while (*scout != '\0')
        {
            if (!std::isspace(*scout++))
            {
                end = scout;
            }
        }

        auto /* std::ptrdiff_t */ const length{ end - begin };
        if (begin != str)
        {
            std::memmove(str, begin, length);
        }

        str[length] = '\0';
    }

    return str;
}
 0
Author: Mitch Laber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-06 23:35:25

Ok to jest moje zdanie na to pytanie. Uważam, że jest to najbardziej zwięzłe rozwiązanie, które modyfikuje ciąg znaków w miejscu (free będzie działać) i unika jakiegokolwiek UB. Dla małych strun jest to prawdopodobnie szybsze rozwiązanie niż memmove.

void stripWS_LT(char *str)
{
    char *a = str, *b = str;
    while (isspace((unsigned char)*a)) a++;
    while (*b = *a++)  b++;
    while (b > str && isspace((unsigned char)*--b)) *b = 0;
}
 0
Author: poby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-06 01:00:01