0

c の文字配列から文字を削除する例を教えてください。頑張りすぎたけど、やりたいことには至らなかった

それが私がしたことです:

 int i;
 if(c<max && c>start) // c is the current index, start == 0 as the index of the start, 
                      //max is the size of the array
 {
                i = c;
      if(c == start)
                        break;

        arr[c-1] = arr[c];


 }
printf("%c",arr[c]);
4

4 に答える 4

4

C の文字配列では、エントリを簡単に削除できません。できることは、データを移動することだけです (たとえば、memmove を使用)。例:

char string[20] = "strring";
/* delete the duplicate r*/
int duppos=3;
memmove(string+duppos, string+duppos+1, strlen(string)-duppos);
于 2010-10-28T16:30:42.477 に答える
1

これが1つのアプローチです。所定の位置にある文字を削除して残りの文字をシャッフルする代わりに(これは面倒です)、保持したい文字を別の配列にコピーします。

#include <string.h>
...
void removeSubstr(const char *src, const char *substr, char *target)
{
  /**
   * Use the strstr() library function to find the beginning of
   * the substring in src; if the substring is not present, 
   * strstr returns NULL.
   */
  char *start = strstr(src, substr);
  if (start)
  {
    /**
     * Copy characters from src up to the location of the substring
     */ 
    while (src != start) *target++ = *src++;
    /**
     * Skip over the substring
     */
    src += strlen(substr);
  }
  /**
   * Copy the remaining characters to the target, including 0 terminator
   */
  while ((*target++ = *src++))
    ; // empty loop body;
}

int main(void)
{
  char *src = "This is NOT a test";
  char *sub = "NOT ";
  char result[20];
  removeSubstr(src, sub, result);
  printf("Src: \"%s\", Substr: \"%s\", Result: \"%s\"\n", src, sub, result);
  return 0;
}
于 2010-10-28T19:07:03.957 に答える
1

文字の配列があります c:

char c[] = "abcDELETEdefg";

"abcdefg" (および null ターミネータ) のみを含む別の配列が必要です。あなたはこれを行うことができます:

#define PUT_INTO 3
#define TAKE_FROM 9
int put, take;
for (put = START_CUT, take = END_CUT; c[take] != '\0'; put++, take++)
{
    c[put] = c[take];
}
c[put] = '\0';

memcpy または memmove を使用してこれを行うより効率的な方法があり、より一般的にすることもできますが、これが本質です。速度が本当に気になる場合は、不要な文字を含まない新しい配列を作成する必要があります。

于 2010-10-28T16:37:34.633 に答える
0

文字列=HELLO\ 0

string_length = 5(または、この呼び出しの外部でキャッシュしたくない場合は、内部でstrlenを使用します

'E'を削除する場合は、remove_char_at_index =1

'E'の位置にコピーします(文字列+ 1)

最初の「L」位置から(文字列+ 1 + 1)

4バイト(NULLを取得したい)なので、5-1 = 4

remove_character_at_location(char * string, int string_length, int remove_char_at_index) {

    /* Use memmove because the locations overlap */.

    memmove(string+remove_char_at_index, 
            string+remove_char_at_index+1, 
            string_length - remove_char_at_position);

}
于 2010-11-01T01:02:28.540 に答える