2016-04-21 57 views
0

在下面的str char數組中,我首先想要找到我看到的第一個數學符號,然後我想倒數並刪除前三個「_」之間的任何內容,並刪除這三個「_」。我能否就如何做到這一點獲得一些想法?刪除字符數組的字符

所以這個:

xa_55_y_*_z_/_+_x_+ 

應該變成:

xa*_z_/_+_x_+ 

我的問題是我不知道如何刪除:

_55_y_ 

這裏是到目前爲止的代碼。

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

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

    char str [] = "xa_55_y_*_z_/_+_x_+"; 
    int length = 0; 
    int decrementor = 0; 
    int underscore_counter = 0; 
    int i = 0; 
    length = strlen (str); 

    for(i = 0; i < length; i++) 
    { 
     decrementor = 0; 
     underscore_counter = 0; 
     if(str[i] == '*' || str[i] == '/' || str[i] == '+' || str[i] == '-') 
     { 
      decrementor = i; 
      while(underscore_counter != 3) 
      { 
       if(str[decrementor] == '_') 
       { 
        underscore_counter++; 
        printf("underscore_counter is %d \n", underscore_counter); 
       } 
       decrementor--; 
      } 
     } 
    } 

    return 0; 
} 
+0

@dreamlax謝謝。 – rockstar797

+0

'if(str [i] =='_')'這怎麼可能是真的?這行代碼在另一個'if'塊中,保證'str [i]'不能被''''''。 – kaylum

+0

@kaylum謝謝。我修正了我的錯誤。 – rockstar797

回答

2

您可以使用strcspn()找到第一家運營商,從而簡化了問題一點點。然後,它只是一個倒退和計數下劃線的事,然後就輸出相應的子串的問題,例如:

int main() 
{ 
    char str [] = "xa_55_y_*_z_/_+_x_+"; 
    size_t firstOp = strcspn(str, "*/+-"); 
    size_t len = strlen(str); 
    size_t i = firstOp; 
    int underscores = 0; 

    // go backwards looking for the underscores (or the beginning of the 
    // string, whichever occurs first) 
    while (i > 0) 
    { 
     if (str[--i] == '_') 
      underscores++; 
     if (underscores == 3) 
      break; 
    } 

    // output the first part of the string up to the third underscore 
    // before the first operator 
    for (size_t j = 0; j < i; j++) 
     putchar(str[j]); 

    // output the rest of the string after and including the operator 
    for (size_t j = firstOp; j < len; j++) 
     putchar(str[j]); 

    // and a linefeed character (optional) 
    putchar('\n'); 
} 

對不起命名不良ij變量,希望這是有道理的。