在 c++ 中将字符串拆分为多个部分
Split String into parts in c++
我刚刚开始学习 c++,我在想他们有什么拆分字符串的方法。莱姆说得更清楚。假设用户输入字符串,出生日期,格式如下dd-mm-yy
。现在我希望将日期、月份和年份存储在 3 个不同的变量中。那我该怎么做??
PS:我用谷歌搜索了一下,发现这可以使用boot::regex
来完成。但是,我仍然想知道是否有更简单的方法可以做到这一点。作为一个初学者阻碍了我。:P无论如何,任何帮助将不胜感激。
简要介绍:
我想要这样的东西。
Enter date: //Accept the date
22-3-17 //Input by user
Date : 22 //Output
Month: 3 //Output
Year : 17 //Output
您可以使用 sscanf 函数:http://en.cppreference.com/w/cpp/io/c/fscanf
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
string date;
cin>>date;
int day, month, year;
sscanf(date.c_str(), "%d-%d-%d", &day, &month, &year);
cout << day << ' ' << month << ' ' << year;
return 0;
}
有不同的方法可以做到这一点。对于"最简单的"方式,我建议将std::string::find((方法(http://www.cplusplus.com/reference/string/string/find/(与std::string::substr((方法(http://www.cplusplus.com/reference/string/string/substr/(结合使用。
对于正则表达式的使用,您不需要 boost:http://www.cplusplus.com/reference/regex/
可以使用运算符 [] 获取字符串的字符。
http://www.cplusplus.com/reference/string/string/operator[]/
这是一个完整的工作程序,它已编译、构建并成功运行在运行 Windows 7 64 位的英特尔酷睿 2 Quad Extreme 上使用 Visual Studio 2015 社区版,该程序已检索 OP 以特定格式请求的信息,适当地解析信息或数据字符串,并以请求或要求的格式显示结果。
stdafx.h
#ifndef STDAFX_H
#define STDAFX_H
#include <vector>
#include <algorithm>
#include <iterator>
#include <tchar.h>
#include <conio.h>
#include <string>
#include <iostream>
#include <iomanip>
enum ReturnCode {
RETURN_OK = 0,
RETURN_ERROR = 1,
}; // ReturnCode
#endif // STDAFX_H
stdafx.cpp
#include "stdafx.h"
实用性.h
#ifndef UTILITY_H
#define UTILITY_H
class Utility {
public:
static void pressAnyKeyToQuit();
static std::string toUpper( const std::string& str );
static std::string toLower( const std::string& str );
static std::string trim( const std::string& str, const std::string elementsToTrim = " tnr" );
static unsigned convertToUnsigned( const std::string& str );
static int convertToInt( const std::string& str );
static float convertToFloat( const std::string& str );
static std::vector<std::string> splitString( const std::string& strStringToSplit, const std::string& strDelimiter, const bool keepEmpty = true );
private:
Utility(); // Private - Not A Class Object
Utility( const Utility& c ); // Not Implemented
Utility& operator=( const Utility& c ); // Not Implemented
template<typename T>
static bool stringToValue( const std::string& str, T* pValue, unsigned uNumValues );
template<typename T>
static T getValue( const std::string& str, std::size_t& remainder );
}; // Utility
#include "Utility.inl"
#endif // UTILITY_H
Utility.inl
// ----------------------------------------------------------------------------
// stringToValue()
template<typename T>
static bool Utility::stringToValue(const std::string& str, T* pValue, unsigned uNumValues) {
int numCommas = std::count(str.begin(), str.end(), ',');
if (numCommas != uNumValues - 1) {
return false;
}
std::size_t remainder;
pValue[0] = getValue<T>(str, remainder);
if (uNumValues == 1) {
if (str.size() != remainder) {
return false;
}
}
else {
std::size_t offset = remainder;
if (str.at(offset) != ',') {
return false;
}
unsigned uLastIdx = uNumValues - 1;
for (unsigned u = 1; u < uNumValues; ++u) {
pValue[u] = getValue<T>(str.substr(++offset), remainder);
offset += remainder;
if ((u < uLastIdx && str.at(offset) != ',') ||
(u == uLastIdx && offset != str.size()))
{
return false;
}
}
}
return true;
} // stringToValue
效用.cpp
#include "stdafx.h"
#include "Utility.h"
// ----------------------------------------------------------------------------
// pressAnyKeyToQuit()
void Utility::pressAnyKeyToQuit() {
std::cout << "Press any key to quit" << std::endl;
_getch();
} // pressAnyKeyToQuit
// ----------------------------------------------------------------------------
// toUpper()
std::string Utility::toUpper(const std::string& str) {
std::string result = str;
std::transform(str.begin(), str.end(), result.begin(), ::toupper);
return result;
} // toUpper
// ----------------------------------------------------------------------------
// toLower()
std::string Utility::toLower(const std::string& str) {
std::string result = str;
std::transform(str.begin(), str.end(), result.begin(), ::tolower);
return result;
} // toLower
// ----------------------------------------------------------------------------
// trim()
// Removes Elements To Trim From Left And Right Side Of The str
std::string Utility::trim(const std::string& str, const std::string elementsToTrim) {
std::basic_string<char>::size_type firstIndex = str.find_first_not_of(elementsToTrim);
if (firstIndex == std::string::npos) {
return std::string(); // Nothing Left
}
std::basic_string<char>::size_type lastIndex = str.find_last_not_of(elementsToTrim);
return str.substr(firstIndex, lastIndex - firstIndex + 1);
} // trim
// ----------------------------------------------------------------------------
// getValue()
template<>
float Utility::getValue(const std::string& str, std::size_t& remainder) {
return std::stof(str, &remainder);
} // getValue <float>
// ----------------------------------------------------------------------------
// getValue()
template<>
int Utility::getValue(const std::string& str, std::size_t& remainder) {
return std::stoi(str, &remainder);
} // getValue <int>
// ----------------------------------------------------------------------------
// getValue()
template<>
unsigned Utility::getValue(const std::string& str, std::size_t& remainder) {
return std::stoul(str, &remainder);
} // getValue <unsigned>
// ----------------------------------------------------------------------------
// convertToUnsigned()
unsigned Utility::convertToUnsigned(const std::string& str) {
unsigned u = 0;
if (!stringToValue(str, &u, 1)) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to unsigned";
throw strStream.str();
}
return u;
} // convertToUnsigned
// ----------------------------------------------------------------------------
// convertToInt()
int Utility::convertToInt(const std::string& str) {
int i = 0;
if (!stringToValue(str, &i, 1)) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to int";
throw strStream.str();
}
return i;
} // convertToInt
// ----------------------------------------------------------------------------
// convertToFloat()
float Utility::convertToFloat(const std::string& str) {
float f = 0;
if (!stringToValue(str, &f, 1)) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to float";
throw strStream.str();
}
return f;
} // convertToFloat
// ----------------------------------------------------------------------------
// splitString()
std::vector<std::string> Utility::splitString( const std::string& strStringToSplit, const std::string& strDelimiter, const bool keepEmpty ) {
std::vector<std::string> vResult;
if ( strDelimiter.empty() ) {
vResult.push_back( strStringToSplit );
return vResult;
}
std::string::const_iterator itSubStrStart = strStringToSplit.begin(), itSubStrEnd;
while ( true ) {
itSubStrEnd = search( itSubStrStart, strStringToSplit.end(), strDelimiter.begin(), strDelimiter.end() );
std::string strTemp( itSubStrStart, itSubStrEnd );
if ( keepEmpty || !strTemp.empty() ) {
vResult.push_back( strTemp );
}
if ( itSubStrEnd == strStringToSplit.end() ) {
break;
}
itSubStrStart = itSubStrEnd + strDelimiter.size();
}
return vResult;
} // splitString
主.cpp
#include "stdafx.h"
#include "Utility.h"
int main () {
std::string date;
std::cout << "Enter Date in DD-MM-YY Format.n" << std::endl;
std::getline( std::cin, date );
std::vector<std::string> vResults = Utility::splitString( date, "-" );
std::cout << "nDate : " << vResults[0] << std::endl
<< "Month: " << vResults[1] << std::endl
<< "Year : " << vResults[2] << std::endl << std::endl;
Utility::pressAnyKeyToQuit();
return 0;
} // main
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- 将 Boost.Spirit.X3 解析器拆分为多个 TU
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- 如何在拆分为多个文件的分层 SM 中退出子机器?(使用boost::MSM)
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 如何使用两个不同的分隔符拆分字符串
- 基于 C++ 中的多个字符串分隔符拆分字符串
- 将英文文本拆分为多个行
- 通过正则表达式拆分字符串会切断结果的第一个字母
- 如何在不将其拆分为两个嵌套循环的情况下打印整个形状?
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 当我将C++类拆分为标头和实现时,我得到了 20 个没有意义的编译器错误
- 尝试使用 Qt 库中的 QPixmap 将图像拆分为多个块。关于他的复制方法的工作方式,我有什么不明白的吗?
- 分解打包的 int 值并将其拆分为两个组件 c++
- C++:用多个分隔符拆分字符串,并在结果中保留分隔符
- 如何在c ++中用多个分隔符拆分LPWSTR并返回LPWSTR数组?
- 如何在c ++中用多个分隔符拆分字符指针并返回字符指针数组?