bool rspfLocalTm::setIso8601(const std::string& timeString, bool shiftToGmtOffsetZero) { rspfDate now; std::string::size_type pos = 0; rspf_int32 year = 0; rspf_int32 month = 0; rspf_int32 day = 0; rspf_int32 timeZoneOffset = 0; if(timeString[0] != 'T') // make sure it's not time only { // look for year // if(readIntegerFromString(year, timeString, pos, 4)) { // retrieved the year portion // now check for separator not digit // // we at least have a year // now check for others setYear(year); if(!isdigit(timeString[pos])) { // skip separator ++pos; } if(readIntegerFromString(month, timeString, pos, 2)) { setMonth(month); if(!isdigit(timeString[pos])) { // skip separator ++pos; } if(readIntegerFromString(day, timeString, pos, 2)) { setDay(day); } } } else { return false; } } else // set year month day to current { setYear(now.getYear()); setMonth(now.getMonth()); setDay(now.getDay()); } // check to see if we need to read time portion if(timeString[pos] == 'T') { ++pos; // skip T character rspf_int32 hours=0, minutes=0; if(readIntegerFromString(hours, timeString, pos, 2)) { setHour(hours); // now check for separator if(!std::isdigit(timeString[pos])) { ++pos; // skip separator if present } if(readIntegerFromString(minutes, timeString, pos, 2)) { setMin(minutes); // now check for time zone if only a hour minute time // if(timeString[pos] == 'Z') { // no adjustment needed } else if(!readTimeZoneOffset(timeZoneOffset, timeString, pos)) { double fractionalSeconds = 0.0; if(!std::isdigit(timeString[pos])) { ++pos; } std::string::size_type endPos = timeString.find_first_not_of("0123456789.", pos); if(endPos == std::string::npos) { fractionalSeconds = rspfString(timeString.begin()+pos, timeString.end()).toDouble(); } else { fractionalSeconds = rspfString(timeString.begin()+pos, timeString.begin()+endPos).toDouble(); } setFloatSec(fractionalSeconds); pos = endPos; if(pos == std::string::npos) { // we will not be too strict so if at the end then just return we got enough return true; } if(timeString[pos] == 'Z') { // no adjustment needed } else { readTimeZoneOffset(timeZoneOffset, timeString, pos); } } } } else { // need at least hours return false; } } else if(std::isdigit(timeString[pos])) { rspf_int32 hours=0, minutes=0; if(readIntegerFromString(hours, timeString, pos, 2)) { setHour(hours); // now check for separator if(!std::isdigit(timeString[pos])) { ++pos; // skip separator if present } if(readIntegerFromString(minutes, timeString, pos, 2)) { setMin(minutes); if(!readTimeZoneOffset(timeZoneOffset, timeString, pos)) { double fractionalSeconds = 0.0; if(!std::isdigit(timeString[pos])) { ++pos; } std::string::size_type endPos = timeString.find_first_not_of("0123456789.", pos); if(endPos == std::string::npos) { fractionalSeconds = rspfString(timeString.begin()+pos, timeString.end()).toDouble(); } else { fractionalSeconds = rspfString(timeString.begin()+pos, timeString.begin()+endPos).toDouble(); } setFloatSec(fractionalSeconds); pos = endPos; if(pos == std::string::npos) { // we will not be too strict so if at the end then just return we got enough return true; } if(timeString[pos] == 'Z') { // no adjustment needed } else { readTimeZoneOffset(timeZoneOffset, timeString, pos); } } } } } else { // need at least hours return false; } if(shiftToGmtOffsetZero && (timeZoneOffset!=0)) { addSeconds(-timeZoneOffset); } return true; }
bool is_comment(const std::string &line){ auto first = line.find_first_not_of(" \t"); return line[first] == ';'; }
static void trimQuotes(std::string &s) { s.erase(0, s.find_first_not_of(' ')); s.erase(s.find_last_not_of(' ')+1); }
long Skini :: parseString( std::string& line, Message& message ) { message.type = 0; if ( line.empty() ) return message.type; // Check for comment lines. std::string::size_type lastPos = line.find_first_not_of(" ,\t", 0); std::string::size_type pos = line.find_first_of("/", lastPos); if ( std::string::npos != pos ) { oStream_ << "// Comment Line: " << line; handleError( StkError::STATUS ); return message.type; } // Tokenize the string. std::vector<std::string> tokens; this->tokenize( line, tokens, " ,\t"); // Valid SKINI messages must have at least three fields (type, time, // and channel). if ( tokens.size() < 3 ) return message.type; // Determine message type. int iSkini = 0; while ( iSkini < __SK_MaxMsgTypes_ ) { if ( tokens[0] == skini_msgs[iSkini].messageString ) break; iSkini++; } if ( iSkini >= __SK_MaxMsgTypes_ ) { oStream_ << "Skini::parseString: couldn't parse this line:\n " << line; handleError( StkError::WARNING ); return message.type; } // Found the type. message.type = skini_msgs[iSkini].type; // Parse time field. if ( tokens[1][0] == '=' ) { tokens[1].erase( tokens[1].begin() ); if ( tokens[1].empty() ) { oStream_ << "Skini::parseString: couldn't parse time field in line:\n " << line; handleError( StkError::WARNING ); return message.type = 0; } message.time = (StkFloat) -atof( tokens[1].c_str() ); } else message.time = (StkFloat) atof( tokens[1].c_str() ); // Parse the channel field. message.channel = atoi( tokens[2].c_str() ); // Parse the remaining fields (maximum of 2 more). int iValue = 0; long dataType = skini_msgs[iSkini].data2; while ( dataType != NOPE ) { if ( tokens.size() <= (unsigned int) (iValue+3) ) { oStream_ << "Skini::parseString: inconsistency between type table and parsed line:\n " << line; handleError( StkError::WARNING ); return message.type = 0; } switch ( dataType ) { case SK_INT: message.intValues[iValue] = atoi( tokens[iValue+3].c_str() ); message.floatValues[iValue] = (StkFloat) message.intValues[iValue]; break; case SK_DBL: message.floatValues[iValue] = atof( tokens[iValue+3].c_str() ); message.intValues[iValue] = (long) message.floatValues[iValue]; break; case SK_STR: // Must be the last field. message.remainder = tokens[iValue+3]; return message.type; default: // MIDI extension message message.intValues[iValue] = dataType; message.floatValues[iValue] = (StkFloat) message.intValues[iValue]; iValue--; } if ( ++iValue == 1 ) dataType = skini_msgs[iSkini].data3; else dataType = NOPE; } return message.type; }
std::string trimLeft (const std::string& in, const std::string& t /*= " "*/) { std::string out = in; return out.erase (0, in.find_first_not_of (t)); }
void ossim::lexQuotedTokens(const std::string& str, ossim_uint32 start, const char* whitespace, const char* quotes, std::vector<std::string>& tokens, bool& unbalancedQuotes) { ossimREQUIRE(whitespace != NULL); ossimREQUIRE(quotes != NULL); ossimREQUIRE(tokens != NULL); const char openQuote(quotes[0]), closeQuote(quotes[1]); tokens.clear(); unbalancedQuotes = false; int end=0; while (start < str.length()) { if (str[start] == openQuote) { int openBraceCount = 1; if (start+1 < str.length()) { start++; if (str[start] != closeQuote) { // end = start+1; end = start; while (static_cast<ossim_uint32>(end) < str.length() && openBraceCount > 0) { if (str[end] == openQuote) openBraceCount++; else if (str[end] == closeQuote) openBraceCount--; end++; } } else { openBraceCount = 0; start++; end = start+1; } } if (openBraceCount == 0) { tokens.push_back(str.substr(start, end-1-start)); } else { unbalancedQuotes = true; end = (int)str.length(); } } else if (str[start] == closeQuote) { unbalancedQuotes = true; end = (int)str.length(); } else { end = (int)str.find_first_of(whitespace, start); tokens.push_back(str.substr(start, end-start)); } start = (ossim_uint32)str.find_first_not_of(whitespace, end); } }
std::string gTrim(const std::string &s) { std::size_t first = s.find_first_not_of(" \n\t"); std::size_t last = s.find_last_not_of(" \n\t"); return s.substr(first, last-first+1); }
std::string trimString(std::string& str) { str.erase(str.find_last_not_of(" ") + 1); return str.erase(0, str.find_first_not_of(" ")); }
void SipperMediaPortable::trim_left(std::string &s, const std::string &t) { s.erase (0, s.find_first_not_of (t)) ; }
std::string Instruction::extractType(const std::string args) { size_t posFirst = args.find_first_not_of(" \t"); size_t posLast = args.find_first_of(" \t(", posFirst); return args.substr(posFirst, posLast - posFirst); }
void trim_left(std::string& source, const std::string& t) { source.erase(0, source.find_first_not_of(t)); }
/// <summary> /// Determines if a given std::string only contains whitespace or is empty /// </summary> /// <param name="original_str">The original std::string</param> /// <returns>True if the original_str only contains whitespace</returns> bool StringFunctions::isOnlyWhitespace(const std::string &original_str) { return original_str.find_first_not_of("\t\n\v\f\r ") == std::string::npos; }
static std::string TrimFromFront( std::string const& stringToTrim, std::string const& charsToTrim ) { return stringToTrim.substr( stringToTrim.find_first_not_of( charsToTrim ), std::string::npos ); }
std::string trimWS(std::string& s){ std::string ws = " \t"; s.erase(0, s.find_first_not_of(ws)); s.erase(s.find_last_not_of(ws)+1); return s; }
bool constant_exprt::value_is_zero_string() const { const std::string val=id2string(get_value()); return val.find_first_not_of('0')==std::string::npos; }
//Removes whitespace from the beginning of the line void trimLeft(std::string& str) { int start = str.find_first_not_of(whitespace); str.erase(0, start); }
std::string sunjwbase::strtrim_left(const std::string& s, const std::string& spaces) { std::string d(s); return d.erase(0, s.find_first_not_of(spaces)); } // end of trim_left
/** * Check for valid address... */ bool valid_address (std::string addr) { return addr.compare(0, 2, "0x") == 0 && addr.size() > 2 && addr.find_first_not_of("0123456789abcdefABCDEF", 2) == std::string::npos; }
void PackedNavBits::rawBitInput(const std::string inString ) throw(InvalidParameter) { // Debug //cout << " ENTERING rawBitInput( )-------------------------------------------------" << endl; // Find first non-white space string. // Should translate as a decimal value. // If so, assume this is the number of bits that follow, but do not // store it until success. // For out purposes, treat space, tab, and comma as white space // (the inclusion of comma allows CSV files to be read). string whiteSpace=" \t,"; string::size_type begin = inString.find_first_not_of(whiteSpace); if (begin==string::npos) { InvalidParameter exc("Did not find #bits at beginning of input string."); GPSTK_THROW(exc); } string::size_type end = inString.find_first_of(whiteSpace,begin); if (end==string::npos) { InvalidParameter exc("Did not find space after #bits at beginning of input string."); GPSTK_THROW(exc); } string textBitCount = inString.substr(begin,end); int bitsExpected = StringUtils::asInt(textBitCount); // Find successive 32 bits quantities stored as hex strings. // That is to say, each should be of the format 0xAAAAAAAA // There should be sufficient to cover the number of input // bits plus padding to the next even 32 bit word boundary. // That is to say, []# of 32 bits words] = ((inBits-1)/32) + 1; int numWordsExpected = (( bitsExpected-1)/32) + 1; int bitsRead = 0; // debug //cout << "bitsExpected, numWordsExpected : " << bitsExpected << ", " << numWordsExpected << endl; for (int i = 0; i<numWordsExpected; ++i) { // For each word, convert the string to a value, then add it // to the packed bit storage. begin = inString.find_first_not_of(whiteSpace,end+1); if (begin==string::npos) { InvalidParameter exc("Did not find expected number of hex words."); GPSTK_THROW(exc); } end = inString.find_first_of(whiteSpace,begin); string::size_type length = end - begin; string hexWord = inString.substr(begin,length); // Debug // cout << "hexWord (string) : '" << hexWord << "'" << endl; if (hexWord.substr(0,2)!="0x" && hexWord.substr(0,2)!="0X" ) { InvalidParameter exc("Expected hex data did not being with '0x'"); GPSTK_THROW(exc); } unsigned long dataWord = StringUtils::x2uint(hexWord); // NOTE: Since the input is always in terms of complete left- // justified 32-bit words, the "numberBits" argument to // addUnsignedLong() is always 32. However, we need to keep // track of how many bits are actually being stored in the // PackedNavBits object. The only word that is not 32-bits // "full" is the last word. int numBitsToAdd = bitsExpected - bitsRead; if (numBitsToAdd>32) numBitsToAdd = 32; // Debug // cout << " dataWord (dec) : " << dataWord << endl; // cout << " numBitsToAdd : " << numBitsToAdd << endl; addUnsignedLong( dataWord, 32, 1); bitsRead += numBitsToAdd; } // Now trim the string and store the final size. bits_used = bitsRead; trimsize(); return; }
bool valid_size (std::string size) { return size.find_first_not_of("0123456789") == std::string::npos; }
std::string CallHprose::DownloadHprose( std::string strHproseDownloadUrl, std::string strFileDir, std::string strFileName ) { CInternetSession sess; CHttpFile* pHttpFile; try { pHttpFile=(CHttpFile*)sess.OpenURL(strHproseDownloadUrl.c_str()); } catch(CException* e) { pHttpFile = 0; TCHAR msg[1024]; memset(msg, 0, 1024); e->GetErrorMessage(msg, 1023, NULL); ZTools::WriteZToolsFormatLog("打开URL失败:%s", msg); return ""; } DWORD dwStatus; DWORD dwBuffLen = sizeof(dwStatus); BOOL bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen); int nReadBlockSize = 256*1024; char* pBuffer = new char[nReadBlockSize]; if( bSuccess && dwStatus>= 200&& dwStatus<300 ) { if (strFileName.length() == 0) { CString sContentDisposition; DWORD dwIndex = 0; bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_DISPOSITION, sContentDisposition, &dwIndex); std::string strContentDisposition((LPCTSTR)sContentDisposition); std::string strKeyBegin("filename=\""); std::string strKeyEnd("\""); if (!strContentDisposition.empty()) { size_t nBegin = strContentDisposition.find(strKeyBegin) + strKeyBegin.length(); if (nBegin < strContentDisposition.length()) { size_t nEnd = strContentDisposition.find(strKeyEnd, nBegin); strFileName = strContentDisposition.substr(nBegin, nEnd - nBegin); } strFileName = deescapeURL(strFileName); ZTools::UTF8ToMB(strFileName); } } if (strFileName.length() == 0) { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("没有找到文件名"); return ""; } std::replace(strFileDir.begin(), strFileDir.end(), '/', '\\'); strFileDir.erase(strFileDir.find_last_not_of('\\') + 1); std::replace(strFileName.begin(), strFileName.end(), '/', '\\'); strFileName.erase(0, strFileName.find_first_not_of('\\')); std::string strFilePath = ZTools::FormatString("%s\\%s", strFileDir.c_str(), strFileName.c_str()); //先下载到临时文件中,下载成功后重命名 std::string strFilePathTemp = ZTools::FormatString("%s\\%s", strFileDir.c_str(), ZTools::GetCurrentTimeString16().c_str()); if (!MakeSureDirectoryPathExists(strFilePath.c_str())) { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("创建文件夹失败:%s", strFilePath.c_str()); return ""; } CFile fileWrite; ULONGLONG dwFileLen = 0; DWORD dwWriteIndex = 0; dwFileLen = pHttpFile->SeekToEnd(); pHttpFile->SeekToBegin(); if(fileWrite.Open(strFilePathTemp.c_str(), CFile::modeWrite|CFile::modeCreate)) { int nCount = 0; while(dwWriteIndex < dwFileLen) { nCount = pHttpFile->Read(pBuffer, nReadBlockSize); fileWrite.Write(pBuffer, nCount); dwWriteIndex += nCount; } fileWrite.Close(); rename(strFilePathTemp.c_str(), strFilePath.c_str()); delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); delete pHttpFile; sess.Close(); if (PathFileExists(strFilePath.c_str())) { return strFilePath; } else { return ""; } } else { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("本地文件%s打开出错", strFilePath.c_str()); return ""; } } else { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("打开网页文件出错,错误码:%d", dwStatus); return ""; } delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); return ""; }
BOOST_FILESYSTEM_DECL bool portable_posix_name(const std::string & name) { return name.size() != 0 && name.find_first_not_of(valid_posix) == std::string::npos; }
void strip(std::string& str) { str.erase(str.find_last_not_of(" ") + 1); //RTrim str.erase(0, str.find_first_not_of(" ")); //LTrim }
/** * @brief remove whitespaces from string * @param str */ void string_trim(std::string &str) { str.erase(0, str.find_first_not_of(" \t\n\r\v")); str.erase(str.find_last_not_of(" \t\n\r\v")+1); }
bool is_blank(const std::string &line){ if (!line.size()) return 1; auto first = line.find_first_not_of(" \t"); return first == line.npos; }
bool FilteredTrace::parse_nmea_string(const std::string& nmea_string) { /* Guarantees that no spaces are inside nmea_string */ /* ... */ /** @todo Think about that later (is it necessary???) */ const std::string ENDLINE = "\n"; const std::string GPGGA_PREFIX("$GPGGA"); const std::string GPRMC_PREFIX("$GPRMC"); const int PREFIX_BEGIN_INDEX = 0; const int PREFIX_LENGTH = 6; const int TIME_BEGIN_INDEX = 7; const int TIME_LENGTH = 6; bool use_gpgga_string = true; bool found_gprmc_string = false; bool found_gpgga_string = false; std::string gpgga_string; std::string gprmc_string; std::string time_string; GPSPoint gps_point; int found_gps_points = 0; std::string::size_type begin_index = nmea_string.find_first_not_of(ENDLINE); if (begin_index == std::string::npos) return false; std::string::size_type end_index = nmea_string.find_first_of(ENDLINE, begin_index); while(end_index != std::string::npos) { std::string nmea_prefix( nmea_string.substr(begin_index + PREFIX_BEGIN_INDEX, PREFIX_LENGTH) ); // std::cout << "nmea_prefix=" << nmea_prefix << "; "; if (nmea_prefix == GPRMC_PREFIX) { // std::cout << "GPRMC; "; if (use_gpgga_string) { // std::cout << "!found_gprmc_string; "; if (!found_gprmc_string) { if (!found_gpgga_string) { // std::cout << "!found_gpgga_string; "; time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH)); gprmc_string.append(nmea_string.substr(begin_index, end_index - begin_index)); found_gprmc_string = true; } else // explicit: if (found_gpgga_string) { // std::cout << "found_gpgga_string; "; gprmc_string.append(nmea_string.substr(begin_index, end_index - begin_index)); if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string) { // std::cout << "same_time; "; if (gps_point.parse_nmea_string(gpgga_string, gprmc_string)) { // std::cout << "parse_gps_point ok; "; push_back(gps_point); ++found_gps_points; } else { mlog(MLog::debug, "FilteredTrace::parse_from_nmea") << "Parsing of NMEA strings fails! (GPGGA and GPRMC strings follows) " << gpgga_string << " " << gprmc_string << "\n"; } found_gprmc_string = false; found_gpgga_string = false; gpgga_string.erase(); gprmc_string.erase(); time_string.erase(); } else // explicit: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) != time_string) { // std::cout << "!same_time; "; gpgga_string.erase(); found_gpgga_string = false; found_gprmc_string = true; time_string.erase(); time_string.append( nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) ); } // end: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string) } // end: if (!found_gpgga_string) } else // explicit: if(found_gprmc_string) { mlog(MLog::info, "FilteredTrace") << "Switching to \"No-GPGGA-Modus\".\n"; use_gpgga_string = false; _gps_points_have_valid_altitudes = false; if (size() > 0) { mlog(MLog::debug, "FilteredTrace") << "Must review GPSPoints.\n"; iterator iter = begin(); iterator iter_end = end(); for (; iter != iter_end; ++iter) { iter->set_altitude(-1.0); /** @todo Define a value for a invalid altitude * (perhaps -1000000, because this value is never reached in * real world!) */ } } if (gps_point.parse_nmea_string("", gprmc_string)) { push_back(gps_point); ++found_gps_points; } if (gps_point.parse_nmea_string("", nmea_string.substr(begin_index, end_index - begin_index))) { push_back(gps_point); ++found_gps_points; } } } else // explicit: if (!use_gpgga_string) { // std::cout << "found_gprmc_string; "; if (gps_point.parse_nmea_string("", nmea_string.substr(begin_index, end_index - begin_index))) { push_back(gps_point); ++found_gps_points; } } // end: if (use_gpgga_string) } else if (use_gpgga_string && (nmea_prefix == GPGGA_PREFIX)) { // std::cout << "GPGGA; "; if (!found_gpgga_string) { // std::cout << "!found_gpgga_string; "; if (!found_gprmc_string) { // std::cout << "!found_gprmc_string; "; time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH)); gpgga_string.append(nmea_string.substr(begin_index, end_index- begin_index)); found_gpgga_string = true; } else // explicit: if (found_gprmc_string) { // std::cout << "found_gprmc_string; "; gpgga_string.append(nmea_string.substr(begin_index, end_index - begin_index)); if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string) { // std::cout << "same_time; "; if (gps_point.parse_nmea_string(gpgga_string, gprmc_string)) { // std::cout << "parse_gps_point ok; "; push_back(gps_point); ++found_gps_points; } else { mlog(MLog::debug, "FilteredTrace::parse_from_nmea") << "Parsing of NMEA strings fails! (GPGGA and GPRMC strings follows) " << gpgga_string << " " << gprmc_string << "\n"; } found_gprmc_string = false; found_gpgga_string = false; gpgga_string.erase(); gprmc_string.erase(); time_string.erase(); } else // explicit: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) != time_string) { // std::cout << "!same_time; "; gprmc_string.erase(); found_gprmc_string = false; found_gpgga_string = true; time_string.erase(); time_string.append( nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) ); } // end: if (nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH) == time_string) } // end: if (!found_gprmc_string) } else // explicit: if (found_gpgga_string) { // std::cout << "found_gpgga_string; "; gpgga_string.erase(); gpgga_string.append(nmea_string.substr(begin_index, end_index - begin_index)); time_string.erase(); time_string.append(nmea_string.substr(begin_index + TIME_BEGIN_INDEX, TIME_LENGTH)); } // end: if (!found_gpgga_string) } // end: if (nmea_prefix == *) begin_index = nmea_string.find_first_not_of(ENDLINE, end_index); if (begin_index == std::string::npos) break; end_index = nmea_string.find_first_of(ENDLINE, begin_index); } // end: while // std::cout << std::endl; return (found_gps_points > 0); }
void trimLeft(std::string &str, std::string delim) { size_t pos = str.find_first_not_of(delim); if (pos != std::string::npos) { str.erase(0, pos); } }
std::string trim (const std::string& str) { const size_t first = str.find_first_not_of(' '); const size_t last = str.find_last_not_of(' '); return str.substr(first, (last - first + 1)); }
bool Document::parseTag(ElementPtr &_currentNode, std::string _content) { // убераем лишнее utility::trim(_content); if (_content.empty()) { // создаем пустой тег if (_currentNode) _currentNode = _currentNode->createChild(""); else { _currentNode = new Element("", 0); // если это первый то запоминаем if (!mRoot) mRoot = _currentNode; } return true; } char simbol = _content[0]; bool tag_info = false; if (simbol == '!') return true; // проверяем на коментарии if (simbol == '?') { // проверяем на информационный тег tag_info = true; _content.erase(0, 1); // удаляем первый символ } size_t start, end; // проверяем на закрытие тега if (simbol == '/') { if (_currentNode == 0) { // чета мы закрывам а ниче даже и не открыто if (!mRoot) { mLastError = ErrorType::CloseNotOpenedElement; return false; } } // обрезаем имя тэга start = _content.find_first_not_of(" \t", 1); if (start == _content.npos) { // тег пустой _content.clear(); } else { end = _content.find_last_not_of(" \t"); _content = _content.substr(start, end - start+1); } // проверяем соответствие открывающего и закрывающего тегов if (_currentNode->getName() != _content) { mLastError = ErrorType::InconsistentOpenCloseElements; return false; } // а теперь снижаем текущий узел вниз _currentNode = _currentNode->getParent(); } else { // выделяем имя до первого пробела или закрывающего тега std::string cut = _content; start = _content.find_first_of(" \t/?", 1); // << превед if (start != _content.npos) { cut = _content.substr(0, start); _content = _content.substr(start); } else _content.clear(); if (_currentNode) _currentNode = _currentNode->createChild(cut); else { if (tag_info) { // информационный тег if (mDeclaration) { mLastError = ErrorType::MoreThanOneXMLDeclaration; return false; } _currentNode = new Element(cut, 0, ElementType::Comment); mDeclaration = _currentNode; } else { // рутовый тег if (mRoot) { mLastError = ErrorType::MoreThanOneRootElement; return false; } _currentNode = new Element(cut, 0, ElementType::Normal); mRoot = _currentNode; } } // проверим на пустоту start = _content.find_last_not_of(" \t"); if (start == _content.npos) return true; // сразу отделим закрывающийся тэг bool close = false; if ((_content[start] == '/') || (_content[start] == '?')) { close = true; // не будем резать строку, просто поставим пробел _content[start] = ' '; // проверим на пустоту start = _content.find_last_not_of(" \t"); if (start == _content.npos) { // возвращаем все назад и уходим _currentNode = _currentNode->getParent(); return true; } } // а вот здесь уже в цикле разбиваем на атрибуты while (true) { // ищем равно start = _content.find('='); if (start == _content.npos) { mLastError = ErrorType::IncorrectAttribute; return false; } // ищем вторые ковычки end = _content.find_first_of("\"\'", start+1); if (end == _content.npos) { mLastError = ErrorType::IncorrectAttribute; return false; } end = _content.find_first_of("\"\'", end+1); if (end == _content.npos) { mLastError = ErrorType::IncorrectAttribute; return false; } std::string key = _content.substr(0, start); std::string value = _content.substr(start+1, end-start); // проверка на валидность if (! checkPair(key, value)) { mLastError = ErrorType::IncorrectAttribute; return false; } // добавляем пару в узел _currentNode->addAttribute(key, value); // следующий кусок _content = _content.substr(end+1); // в строке не осталось символов start = _content.find_first_not_of(" \t"); if (start == _content.npos) break; mCol += start; }; // был закрывающий тег для текущего тега if (close) { // не проверяем имена, потому что это наш тэг _currentNode = _currentNode->getParent(); } } return true; }
void IO:: TrimLeadingWhitespace(std::string &rStr) { string::size_type front = rStr.find_first_not_of(" \t\r\n"); rStr.erase(0, front); }