簡體   English   中英

消除標點和空格

[英]Eliminate punctuations and whitespace

我是c ++編程的新手,想編寫一個具有以下要求的程序:

鑒於文本由

  • 數字
  • 標點符號
  • 空格。

過濾掉不在0..9a..zA..Z范圍內的任何字符。

這意味着當我輸入時:

The quick brown fox jumps over the lazy dog!

輸出將是:

Thequickbrownfoxjumpsoverthelazydog

我輸入了以下代碼並嘗試運行它,結果很好。 但是,當我將其提交到另一個c ++平台以檢查有效性時,沒有生成輸出。

我很困惑......如果可以,請幫忙。 非常感謝大家。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string line;
    getline(cin, line);
    for (int i = 0; i < line.size(); ++i)
    {
        if (!((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || (line[i] >= '0' && line[i] <= '9')))
        {
            line[i] = '\0';
        }
    }
    cout << line;
    return 0;
}

如果你想刪除字母數字以外的字符 ,更好的選擇是使用擦除刪除習語

  1. 使用std::isalnum檢查字符串中的字符是字母還是數字 如果將其打包為一元謂詞( lambda函數 ),則可以應用以下算法函數。
  2. 使用std::remove_if和上面提到的謂詞,收集字符串中必須刪除的所有字符。
  3. 最后,使用std::string::erase刪除std::remove_if收集的所有字符。

如下所示: 在此處查看演示

#include <cctype>     // std::isalnum
#include <algorithm>  // std::remove_if

std::string str{ "The quick brown fox jumps over the lazy dog!" };

// predicate to check the charectors
const auto check = [](const char eachCar)->bool { return !std::isalnum(eachCar); };

// collect the chars which needed to be removed from the string
const auto charsToRemove = std::remove_if(str.begin(), str.end(), check);

// erase them out
str.erase(charsToRemove, str.end());

免責聲明 :上述解決方案並不包括OP的關注(@john在他的回答中已經解釋得很好),而是對未來的讀者有所幫助。

您的代碼只是將一個字符替換為另一個字符。 從字符串中刪除字符的簡單方法是使用erase方法。 像這樣的東西

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    string line;
    getline(cin, line);
    for (int i = 0; i < line.size(); )
    {
        if (!((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z')||(line[i] >= '0' && line[i]<='9')))
        {
            line.erase(i, 1);
        }
        else
        {
            ++i;
        }
    }
    cout << line; 
    return 0;
}

請注意,當我們不擦除字符時,代碼只會向i添加一個,否則在刪除字符后跳過該字符,因為字符串現在縮短了一個。

\\0是字符串的結尾,因此當您使用它時,您將在第一次出現時切斷字符串。

你最好從你的數組中刪除那個char,但是我建議你從最后回到開頭:

偽代碼:

for i = size(line)-1 back to i = 0:
  if line[i] in ('a'-'z', 'A'-'Z', ...):
    for j = i to size(line)-1:
      line[j] = line[j+1]
   reduce_by_the_last_character(line)

暫無
暫無

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

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