如何在C ++中从字符串中提取几组动态数?

问题描述

我想从一个字符串中提取几组数字,然后将它们分别粘贴到另一个字符串中。

假设有一个对话框,我们将WndCaption作为字符串A(输入字符串)获得。

字符串A:Voltage: 2.0V,Current:0.4A,Resistance: 5.0Ω,Power: 1.5W.

字符串A是动态输入,它取决于对话框的WndCaption。例如,字符串A也可以是The apple is inside column: 12,row: 3,Box: 5.

字符串B(输入参考字符串)与字符串A完全相同,只是数字被定界符代替。用于从字符串A中提取数字。

字符串B:Voltage: %fV,Current:%fA,Resistance: %fΩ,Power: %fW.

然后是String C(输出参考字符串)

字符串C:The answers are %fV; %fA; %fΩ; %fW.

字符串B和字符串C配对使用std::vector<>::data数据库(.txt文件获取

问题是:如何提取这4组数字并将其粘贴到字符串C中,并最终获得The answers are 2.0V; 0.4A; 5.0Ω; 1.5W.输出

我试图实现split and merge方法,但是这种情况似乎是不可能的。有想法吗?

解决方法

您绝对应该使用regex来执行该任务。它们更加灵活,可以解析almost anything

如果格式非常有限,并且永远不会更改,则可以使用sscanf来摆脱。这是一个示例程序:

#include <iostream>
#include <string>

int main()
{
   char input[100];
   int param1,param2,param3;
   char output[100];

   sprintf( input,"%s","AA123BBB45CCCCC6789DDDD" ); // your input

   sscanf( input,"AA%dBBB%dCCCCC%dDDDD",&param1,&param2,&param3); // parse the parameters
   
   sprintf(output,"E%dFF%dGGG%dHHHH",param1,param3); // print in output with your new format
   
   printf("%s",output);
    
   return(0);
}

后期编辑:

这个答案已经没有任何意义了,但我会这样保留。

我的建议仍然是:使用正则表达式

,

下面我以代码实现为例,该怎么做。

我不知道完成任务的确切步骤,但是我了解到您需要做两件事-首先使用正则表达式或某些东西在输入字符串中查找并提取某个子字符串的匹配项,其次通过将一些字符串放入其中在第一阶段发现子串。

在下面的代码中,我实现了两个阶段-首先使用正则表达式提取子字符串,然后组成新字符串。

我使用了标准C ++模块std::regex中的函数和对象。另外,我还编码了一个特殊的辅助函数string_format(format,args...)以便能够对合成结果进行格式化,可以通过described here格式化说明符来实现格式化。

您可以通过首先提取必要的子字符串和组合结果格式的字符串来重复几次下一个代码来实现您的目标。

下一个代码can be also run online here!here!

#include <regex>
#include <string>
#include <regex>
#include <iostream>
#include <stdexcept>
#include <memory>

using namespace std;

// Possible formatting arguments are described here https://en.cppreference.com/w/cpp/io/c/fprintf
template<typename ... Args>
std::string string_format( const std::string& format,Args ... args )
{
    size_t size = snprintf( nullptr,format.c_str(),args ... ) + 1; // Extra space for '\0'
    if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
    std::unique_ptr<char[]> buf( new char[ size ] ); 
    snprintf( buf.get(),size,args ... );
    return std::string( buf.get(),buf.get() + size - 1 ); // We don't want the '\0' inside
}

int main() {
    try {
        string str = "abc12345DEF xyz12ABcd";
        
        cout << "Input string [" << str << "]." << endl;
        
        string sre0 = "\\d+[A-Z]+";
        // https://en.cppreference.com/w/cpp/header/regex
        std::regex re0(sre0);
        
        vector<string> elems;
        
        std::sregex_token_iterator iter(str.begin(),str.end(),re0,0);
        std::sregex_token_iterator end;

        while (iter != end)  {
            elems.push_back(*iter);
            ++iter;
            cout << "matched [" << elems.back() << "] " << endl;
        }
        
        string fmt = "New String part0 \"%s\" and part1 \"%s\" and some number %d.";
        string formatted = string_format(fmt.c_str(),elems.at(0).c_str(),elems.at(1).c_str(),987);
        
        cout << "Formatted [" << formatted << "]." << endl;
        
        return 0;
    } catch (exception const & ex) {
        cout << "Exception: " << ex.what() << endl;
        return -1;
    }
}

代码输出:

Input string [abc12345DEF xyz12ABcd].
matched [12345DEF] 
matched [12AB] 
Formatted [New String part0 "12345DEF" and part1 "12AB" and some number 987.].