Clear space string

1. Clear a space in the right strings

 From the end of the string began to find non-space, the next character can be set to 0.

// Clear a space on the right
#include<stdio.h> 
int main ()
{
    char buf[] = "hello world      ";
    int len = 0;
    
    //calculate the length of string
    while(buf[len++]);
    only - ;
    
    int i;
    for(i = len - 1; i >= 0; i--)
    {
        if(buf[i] != ' ')
        {
            buf[i+1] = 0;  // == buf[i+1] = '\0'
            break;
        }
    }
    printf("buf = %s\n",buf);
    return 0;
}

2. Clear the string of spaces left.

  • String left to determine how many spaces;
  • The string overall number of spaces left
  • The last location string 0
// Clear the space left
#include<stdio.h>
int main ()
{
    char buf[256] = "   hello world";
    int len = 0;
    while(buf[len++] == ' ');
    only - ;
    
    int i = len;
    while(buf[i])
    {
        buf[i - len] = buf[i];
        i++;
    }
    buf [i - s] = 0 ;
    printf("buf = %s\n",buf);
    return 0;
 } 

 

Guess you like

Origin www.cnblogs.com/wanghao-boke/p/11031033.html