,删除指定的字符的字符串的有效方式字符串、字符、有效、方式

2023-09-11 04:59:09 作者:南风草木香

例如,鉴于 #1是对每一位的,并删除AEIOU的海峡, 功能要转变STR为 Stckvrflw小号FR何苦ñ的

For example, given a str of "Stackoverflow is for every one" and remove of "aeiou", the function should transform str to "Stckvrflw s fr vry n".

我有字符串中的一个字符数组:海峡[] 和字符中的一个字符数组被删除:删除[]

I have one char array of string: str[] and one char array of chars to be removed:remove[]

我的解决方案:循环STR []寻找每个字符删除[]。移海峡[]一个位置留给每一个时间。我相信更好的黑客是可能的。

My Solution: Loop str[] looking for each in character in remove[]. Shift str[] one place left every-time. I am sure better hack are possible.

推荐答案

移整个字符串留下一个地方将有效地使这是一个为O​​(n ^ 2)算法。您可以就地做到这一点,在线性时间:

Shifting the entire string left one place will make this an O(n^2) algorithm effectively. You can do this in-place, in linear time:

void Remove (char * src, const char * match) {
   char * dest = src;
   for (;;) { 
      char ch = *src++; 
      if (!strchr (match, ch)) *dest++ = ch;  // Copy chars that don't match
      if (!ch) break;                         // Stop when we copy over a null  
   }
}

我假设在这里,这些都是空值终止。如果不是这种情况,则必须通过在长度以及并适当地修改的算法。特别是,你将无法使用,和strchr。只是为了完整性,这里有一个与字符数组工作(不是空终止)。

I'm assuming here that these are null terminated. If this is not the case, then you have to pass in the lengths as well and modify the algorithm appropriately. In particular, you will not be able to use strchr. Just for completeness, here's a version that works with char arrays (not null-terminated).

// Removes from str[] (of length strlen), all chars that are found
// in match[] (of length matchlen). Modifies str in place, and returns
// the updated (shortened) length of str. 
int Remove (char[] str, int srclen, char[] match, int matchlen) {
   int dst = 0, found;
   for (int src = 0; src < srclen; src++) { 
      char ch = str[src];  
      found = 0;           // Search if this char is found in match
      for (int i = 0; i < matchlen && !found; i++) 
         if (match[i] == ch) found = 1;
      if (!found) str[dst++] = ch;
   }
   return dst;
}

最后,这是接近O(n)的,因为我们要得到,我猜。我假设8位字符,并在这里建立一个查表所以这应该为O(n)+ O(m),其中m为匹配字符串的长度运行。

And finally, this is as close to O(n) as we are going to get, I guess. I'm assuming 8 bit chars here and building a look-up table so this should run in O(n) + O(m) where m is the length of the match string.

int Remove (char* str, int srclen, char* match, int matchlen) {
   bool found[256];
   for (int i = 0; i < 256; i++) found[i] = 0;
   for (int i = 0; i < matchlen; i++) found[match[i]] = 1; 

   int dst = 0;
   for (int src = 0; src < srclen; src++) { 
      char ch = str[src];  
      if (!found[ch]) str[dst++] = ch;
   }
   return dst;
}
 
精彩推荐
图片推荐