我有以下代碼:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
string s;
//file contains the following
//id="123456789"
//Note: There is no spaces at the end
file.open("test.txt", ios::in);
getline(file, s);
s = s.substr(s.find("\"") 1, s.length()-1);
cout << s << endl;
return 0;
}
結果列印:
123456789"
為什么最后有引號?奇怪的是,當我將 s.length()-1 更改為 s.length()-5 時,代碼會按照我想要的方式作業。這里有什么問題?
uj5u.com熱心網友回復:
的第二個引數string::substr()是count,而不是index,就像您對待它一樣。
在您的示例中,s.length()=14, 因此您要求從第一個字符 ( )14-1=13之后的索引開始的字符,但從該位置開始只剩下 10 個字符。這就是為什么第二個字符包含在子字串中的原因。 1"3 1=4"
string::find()再次使用找到第二個"字符的索引,然后將兩個索引相減得到它們之間的長度,例如:
auto start = s.find('\"') 1;
auto stop = s.find('\"', start);
s = s.substr(start, stop-start);
start將是 1第一個"字符 ( 3 1=4) 之后stop的索引,并將是第二個"字符 ( 13) 的索引。因此,您得到的長度是13-4=9字符。
處理此問題的另一種方法是將string放入 anistringstream然后使用std::quotedI/O 操縱器提取字符之間的子字串",例如:
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream file("test.txt");
string s;
getline(file, s);
istringstream iss(s);
iss.ignore(3);
iss >> quoted(s);
cout << s << endl;
return 0;
}
uj5u.com熱心網友回復:
該運算式s.length()-1產生除一個字符外的整個字串的長度。
你應該寫例如
auto n = s.find("\"");
s = s.substr( n 1, s.length() - n - 2 );
或者你可以這樣寫
auto n = s.find( '"' );
s = s.substr( n 1, s.rfind( '"' ) - n - 1 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488810.html
上一篇:如何在Javascript中使用正則運算式獲取電話號碼的最后四位?[復制]
下一篇:在C中更改字串中特定字符的顏色
