簡體   English   中英

在字符串的偶數位置提取字母?

[英]extraction of letters at even positions in strings?

string extract(string scrambeledword){ 

unsigned int index;
string output;
string input= " ";

for (index=0; index <= scrambeledword.length() ; index++);
{
    if (index%2==0)
    {  
        output+=input ; 
        cout << output; 

    }


}

return output;}

我想從用戶輸入的40個字母長的單詞中提取偶數編號的索引字母。 這有意義嗎? 我還沒有采取數組,也不想包括它們。

問題:
1.你有一個; for循環之后,循環主體將永遠不會運行。
2. <=這里是錯誤的,因為scrambeledword.length()超出范圍。 使用!=<代替。
3.您需要先為input分配一些內容,然后再將其添加到輸出中,或者完全刪除它。
4.正如@Aconcagua指出的,值得注意的是,我從函數作用域中刪除了index聲明,僅將其添加到for循環作用域中。 如果您還考慮這樣做,則編譯器將引發錯誤(因為在for的范圍外未聲明它),因此您會注意到有關; 問題。

固定版本:

string extract(const string &scrambeledword){ // copying strings is expensive

  // unsigned int index;   // obsolete
  string output;
  // string input= " ";    // obsolete

  for (size_t index = 0; index != scrambeledword.length(); ++index) // `<=` would be wrong since scrambeledword.length() is out of range
  {
    if (index % 2 == 0)
    {
      output += scrambeledword[index];
      // cout << output; // obsolete. If you just want the characters, print scrambeledword[index]
      cout << scrambeledword[index];
    }
  }
  cout << endl; // break the line for better readability 
  return output;
}

您的代碼不會在for下運行該代碼塊,因為其中包含; 在該行的末尾。 這意味着for運行無障礙。 基本上,它將取決於給定單詞的長度。

在for index <= scrambeledword.length()可能導致超出范圍的異常,因為您可以在字符串數組之外進行索引。 改用index < scrambeledword.length()

這可以很好地解決該問題:

string extract(const string& scrambeledword)
{
    string output;

    for (unsigned int index = 0; index < scrambeledword.length(); index++)
    {
        if (index % 2 == 0)
        {
            output += scrambeledword[index];
        }
    }

    return output;
}
auto str = "HelloWorld"s;
int  i   = 0;
for_each(str.cbegin(), str.cend(), [&i](char const & c) { if (i++ % 2 == 0) cout << c; });

輸出: Hlool

你可以這樣:

for(int i = 0; i < scrambleword.length(); i+=2){
        output += scrambleword.at(i);
}

暫無
暫無

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

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