programing

C의 문자열에서 지정된 인덱스의 문자를 제거하려면 어떻게 해야 합니까?

randomtip 2022. 9. 30. 09:39
반응형

C의 문자열에서 지정된 인덱스의 문자를 제거하려면 어떻게 해야 합니까?

문자열에서 문자를 삭제하려면 어떻게 해야 하나요?

끈이 있으면"abcdef"제거하려고 합니다."b"그걸 어떻게 하는 거죠?

다음 코드를 사용하면 첫 번째 문자를 쉽게 제거할 수 있습니다.

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

int main()
{
   char word[] = "abcdef";
   char word2[10];

   strcpy(word2,&word[1]);

   printf("%s\n", word2);

   return 0;
}

그리고.

strncpy(word2,word,strlen(word)-1);

마지막 글자가 없는 문자열이 나오는데 문자열 중간에 있는 문자를 제거하는 방법을 아직 모르겠어요.

memmove 중복되는 영역에 대응할 수 있습니다.그런 것을 시험해 보겠습니다(테스트되지 않은 문제, 아마 +-1 문제).

char word[] = "abcdef";  
int idxToDel = 2; 
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

이전:"abcdef"

그 후:"abdef"

다음을 시도해 보십시오.

void removeChar(char *str, char garbage) {

    char *src, *dst;
    for (src = dst = str; *src != '\0'; src++) {
        *dst = *src;
        if (*dst != garbage) dst++;
    }
    *dst = '\0';
}

테스트 프로그램:

int main(void) {
    char* str = malloc(strlen("abcdef")+1);
    strcpy(str, "abcdef");
    removeChar(str, 'b');
    printf("%s", str);
    free(str);
    return 0;
}

결과:

>>acdef

지정된 문자를 모두 제거하는 방법:

void RemoveChars(char *s, char c)
{
    int writer = 0, reader = 0;

    while (s[reader])
    {
        if (s[reader]!=c) 
        {   
            s[writer++] = s[reader];
        }

        reader++;       
    }

    s[writer]=0;
}

이런 게 안 올라오다니 정말 놀랍네요.

strcpy(&str[idx_to_delete], &str[idx_to_delete + 1]);

매우 효율적이고 심플합니다. strcpy사용하다memmove대부분의 구현에 사용됩니다.

char a[]="string";
int toBeRemoved=2;
memmove(&a[toBeRemoved],&a[toBeRemoved+1],strlen(a)-toBeRemoved);
puts(a);

이것을 시험해 보세요.memmove가 겹칩니다.테스트 완료.

다음은 첫 번째 string 인수에서 두 번째 string 인수로 발생하는 모든 문자를 삭제함으로써 문제를 조금 확장합니다.

/*
 * delete one character from a string
 */
static void
_strdelchr( char *s, size_t i, size_t *a, size_t *b)
{
  size_t        j;

  if( *a == *b)
    *a = i - 1;
  else
    for( j = *b + 1; j < i; j++)
      s[++(*a)] = s[j];
  *b = i;
}

/*
 * delete all occurrences of characters in search from s
 * returns nr. of deleted characters
 */
size_t
strdelstr( char *s, const char *search)
{ 
  size_t        l               = strlen(s);
  size_t        n               = strlen(search);
  size_t        i;
  size_t        a               = 0;
  size_t        b               = 0;

  for( i = 0; i < l; i++)
    if( memchr( search, s[i], n))
      _strdelchr( s, i, &a, &b);
  _strdelchr( s, l, &a, &b);
  s[++a] = '\0';
  return l - a;
}

이 코드는 문자열에서 입력한 모든 문자를 삭제합니다.

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

#define SIZE 1000

char *erase_c(char *p, int ch)
{
    char *ptr;

    while (ptr = strchr(p, ch))
        strcpy(ptr, ptr + 1);

    return p;
}

int main()
{
    char str[SIZE];
    int ch;

    printf("Enter a string\n");
    gets(str);
    printf("Enter the character to delete\n");
    ch = getchar();

    erase_c(str, ch);

    puts(str);

    return 0;
}

입력

a man, a plan, a canal Panama

산출량

 A mn,  pln,  cnl, Pnm!

Edit : 코드를 갱신했습니다.zstring_remove_chr()도서관의 최신 버전에 따르면

ZString이라고 불리는 C용 BSD 라이선스 문자열 처리 라이브러리

https://github.com/fnoyanisi/zString

문자 삭제 기능

int zstring_search_chr(char *token,char s){
    if (!token || s=='\0')
        return 0;

    for (;*token; token++)
        if (*token == s)
            return 1;

    return 0;
}

char *zstring_remove_chr(char *str,const char *bad) {
    char *src = str , *dst = str;

    /* validate input */
    if (!(str && bad))
        return NULL;

    while(*src)
        if(zstring_search_chr(bad,*src))
            src++;
        else
            *dst++ = *src++;  /* assign first, then incement */

    *dst='\0';
    return str;
}

Exmaple 사용 현황

   char s[]="this is a trial string to test the function.";
   char *d=" .";
   printf("%s\n",zstring_remove_chr(s,d));

출력 예

  thisisatrialstringtotestthefunction

\0을(를) 삭제하는 간단하고 빠른 방법은 strcpy 대신 strncpy를 사용하여 마지막 문자(\0) 없이 문자열을 복사하는 것입니다.

strncpy(newStrg,oldStrg,(strlen(oldStrg)-1));
int chartoremove = 1;

strncpy(word2, word, chartoremove);
strncpy(((char*)word2)+chartoremove, ((char*)word)+chartoremove+1,
    strlen(word)-1-chartoremove);

지옥같이 못생겼다

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

int main(){
    char ch[15],ch1[15];
    int i;
    gets(ch);  // the original string
    for (i=0;i<strlen(ch);i++){  
        while (ch[i]==ch[i+1]){ 
            strncpy(ch1,ch,i+1); //ch1 contains all the characters up to and including x
            ch1[i]='\0'; //removing x from ch1
            strcpy(ch,&ch[i+1]);  //(shrinking ch) removing all the characters up to and including x from ch
            strcat(ch1,ch); //rejoining both parts
            strcpy(ch,ch1); //just wanna stay classy
        }
    }
    puts(ch);
}

x가 삭제할 문자의 "기호"라고 가정해 보겠습니다.제 생각은 문자열을 두 부분으로 나누는 것이었습니다.

첫 번째 부분은 인덱스 0에서 대상 문자 x까지 모든 문자를 카운트합니다.

두 번째 부분은 x 뒤의 모든 문자를 카운트합니다(x 제외).

이제 두 부분을 다시 결합하기만 하면 됩니다.

사용하다strcat()문자열을 연결합니다.

그렇지만strcat()는 중복을 허용하지 않으므로 출력을 유지할 새 문자열을 생성해야 합니다.

로 시도했다.strncpy()그리고.snprintf().

int ridx = 1;  
strncpy(word2,word,ridx);   
snprintf(word2+ridx,10-ridx,"%s",&word[ridx+1]);

memmove()를 index() 및 sizeof()와 함께 사용하는 다른 솔루션:

char buf[100] = "abcdef";
char remove = 'b';

char* c;
if ((c = index(buf, remove)) != NULL) {
    size_t len_left = sizeof(buf) - (c+1-buf);
    memmove(c, c+1, len_left);
}

buf[]에 "acdef"가 포함되었습니다.

인덱스를 통과하면 이것이 가장 빠른 방법 중 하나일 수 있습니다.

void removeChar(char *str, unsigned int index) {
    char *src;
    for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
    *src = '\0';
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
void dele_char(char s[],char ch)
{
    int i,j;

    for(i=0;s[i]!='\0';i++)
    {
        if(s[i]==ch)
        {
            for(j=i;s[j]!='\0';j++)
            s[j]=s[j+1];
            i--;
        }
    }
}

int main()
{
    char s[MAX],ch;
    printf("Enter the string\n");
    gets(s);
    printf("Enter The char to be deleted\n");
    scanf("%c",&ch);
    dele_char(s,ch);
    printf("After Deletion:= %s\n",s);
    return 0;
}

카운터가 색인일 때 찾는 항목입니다.

#include <stdio.h>

int main(){

    char str[20];
    int i,counter;
    gets(str);
    scanf("%d", &counter);

    for (i= counter+1; str[i]!='\0'; i++){
        str[i-1]=str[i];
    }
    str[i-1]=0;
    puts(str);



    return 0;
}

매우 오래된 질문이라는 것을 알고 있습니다만, 실장은 여기서 마치겠습니다.

char    *ft_strdelchr(const char *str,char c)
{
        int   i;
        int   j;
        char  *s;
        char  *newstr;

        i = 0;
        j = 0;
        // cast to char* to be able to modify, bc the param is const
        // you guys can remove this and change the param too
        s = (char*)str;
        // malloc the new string with the necessary length. 
        // obs: strcountchr returns int number of c(haracters) inside s(tring)
        if (!(newstr = malloc(ft_strlen(s) - ft_strcountchr(s, c) + 1 * sizeof(char))))
                return (NULL);
        while (s[i])
        {
                if (s[i] != c)
                {
                        newstr[j] = s[i];
                        j++;
                }
                i++;
        }
        return (newstr);
}

삭제할 문자와 동일하지 않은 문자를 새 문자열에 던지기만 하면 됩니다.

다음을 수행합니다.

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

int main (int argc, char const* argv[])
{
    char word[] = "abcde";
    int i;
    int len = strlen(word);
    int rem = 1;

    /* remove rem'th char from word */
    for (i = rem; i < len - 1; i++) word[i] = word[i + 1];
    if (i < len) word[i] = '\0';

    printf("%s\n", word);
    return 0;
}

기본적인 방법은 다음과 같습니다.

void remove_character(char *string, int index) {
   for (index; *(string + index) != '\0'; index++) {
      *(string + index) = *(string + index + 1);
   }
}

언급URL : https://stackoverflow.com/questions/5457608/how-to-remove-the-character-at-a-given-index-from-a-string-in-c

반응형