簡體   English   中英

如何從 c 字符串中刪除特定字符而不轉換為字符串?

[英]How to delete specific character from c string without converting to string?

我正在嘗試從 c 字符串中刪除在 c 字符串中出現兩次的特定字符 (:),而不將其轉換為字符串。

到目前為止,我嘗試執行以下操作,但它刪除了 (:) 之后的每個字符,這不是我想要做的。 我只是想去掉那個特定的角色。

// cString = 09:24:46

for (int i = 0; i < strlen(cString); i++){
        cString[2] = '\0';
        cString[5] = '\0';
    }
//current output: 09
//desired output: 092446

我應該使 cString[2] 和 cString[5] 等於什么? 我嘗試將它們等於 NULL 但我得到相同的 output 我也嘗試了空格但我希望 output 沒有空格

您無需將 C 樣式字符串轉換為std::string即可“刪除”字符。

您可以使用std::remove算法 function:

#include <algorithm>
#include <iostream>
#include <cstring>

int main()
{
  char cString[] = "09:24:46";
  std::cout << cString << "\n";

  // "Remove" the ':' from the C-style string.  
  // pos will point to the beginning of the "removed" elements 
  auto pos = std::remove(cString, cString + strlen(cString), ':');
  
  // overwrite the removed elements with 0 
  while (*pos)
     *pos = '\0';

  std::cout << cString;
} 

Output:

09:24:46
092446

字符數組中的 '\0' 表示它正在結束。 它不會再打印任何字符。

您可以將所有剩余的字符向后移動一個索引並將最后一個字符標記為“\0”(空)。

像這樣:

for(int i = 0;i < n;i++){
     if(cString[i] == ':'){
         for(int j = i;j < n-1;j++){
               cString[j] = cString[j+1];
         }
         cString[n-1] = '\0';
         break;
     }
}
const size_t n = strlen(cString);
for (size_t i = 0, j = 0; j <= n; j++) {
  if (cString[j] != ':')
    cString[i++] = cString[j];
}

暫無
暫無

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

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