簡體   English   中英

是否存在將字符的所有實例復制到另一個字符串的相同索引中的函數?

[英]Is there a function that copies all instances of a character into same indices in another string?

本質上,我正在尋找的是一個標准函數,它可以執行以下操作

void transcpy(char *target, const char *src, const char c)
{
    for (int i = 0; i < strlen(target)+1; i++)
        if (src[i] == c) target[i] = c;
}

這個特定的示例假定targetsrc的長度相同,但這並不是我要查找的內容的必要先決條件。 盡管c假定出現在src

例如transcpy(word, "word", 'r");其中單詞為"____"會將單詞突變為"__r_"

這可能只適用於實施man子手游戲,但似乎足夠有用,可能具有標准實現

我認為標准庫中沒有一個函數可以執行此操作,我將其實現為:

char *replace_by_c(char *dest, const char *src, size_t size, char c) {
  for (size_t i = 0; i < size; i++) {
    if (src[i] == c) {
      dest[i] = c;
    }
  }
  return dest;
}

在C語言中,通常讓函數的用戶處理正確的大小。

char str_one[42];
char str_two[84];

size_t min = MIN(sizeof str_one, sizeof str_two);
replace_by_c(str_one, str_two, min, 'c');

這使函數可以在很多情況下使用,例如,該函數可以在不終止NUL的情況下工作,並且可以將c字符作為NUL處理。

replace_by_c(dest, src, 42, '\0');

這是一個可能的實現,它會在兩個字符串長度不相同時進行處理

char *transcpy(char *dest, const char *src, char c)
{
    size_t shortest = strlen(dest);

    if( strlen( dest ) > strlen(src ) )
        shortest = strlen( src );

    for (size_t i = 0; i < shortest; i++)
    {
        if( c == src[i])
        {
            dest[i] = c;
        }
    }

    return dest;
} // end function: transcpy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM