簡體   English   中英

為什么它給了我錯誤的索引

[英]Why it gives me a wrong index

這是正文

"Abraham, Yohannes A.", 員工,

我想要第二個逗號的索引

這是我的代碼int foundStatus = tempString.find_first_of(",", 8);

我認為這將返回索引 8 之后的第二個逗號的索引,即 22,但是當我給我 -1 時

您需要使用 9 作為第二個參數而不是 8 調用std::string::find_first_of (假設您的字符串是: "\\"Abraham, Yohannes A.\\", Employee, " )。 否則它只會返回 8 而不是 22。返回值std::string::npos (-1) 意味着它之后找不到任何逗號 - 檢查你的輸入字符串兩次,位置 8 之后真的有第二個逗號。

以下代碼將正確輸出 22:

#include <iostream>
#include <string>

int main(int argc, char* argv[]){
  std::string tempString = "\"Abraham, Yohannes A.\", Employee, ";
  size_t firstComma = tempString.find_first_of(","); // firstComma = 8
  if (firstComma != std::string::npos) {
    size_t secondComma = tempString.find_first_of(",", firstComma+1);  // secondComma = 22
    std::cout << secondComma << std::endl;
  }
  return 0;
}

暫無
暫無

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

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