You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用C++实现提取字符串数字并去除特殊符号的函数?

Fixing Your C++ String Processing Function

Hey there! Let's get your string conversion working right. You want to take a string like s1 = "[1 -2.5 3;4 5.25 6;7 8 9.12]" and turn it into a space-separated list of numbers: 1 -2.5 3 4 5.25 6 7 8 9.12. Let's first break down why your current code isn't working, then walk through two solid solutions.

What's Wrong With Your Current Code?

Your approach has a few key issues that throw off the logic:

  • s.find(" ") and s.find(";") only return the first occurrence of those characters. Using them in a loop won't catch all instances, especially since you're modifying the string with erase() which shifts character positions entirely.
  • s.erase(0,i-1) is deleting large chunks of the string mid-loop, making subsequent iterations reference the wrong characters.
  • You're outputting endl instead of spaces, which would create new lines instead of the space-separated format you need.
  • You never handle the closing ] at the end of the string, so it would still be included in your output.

Feasible Implementation Approaches

Here are two straightforward ways to achieve your goal:

Approach 1: Iterate Through Characters (Beginner-Friendly)

This method is simple, easy to follow, and doesn't require advanced features. We'll break the problem into small steps:

  1. Strip the opening [ and closing ] from the input string.
  2. Loop through each character in the remaining string:
    • Replace any ; with a space.
    • Keep all other characters (numbers, decimals, negative signs, existing spaces) as-is.

Code Example:

#include <iostream>
#include <string>
using namespace std;

string processNumericString(const string& input) {
    string result;
    
    // Step 1: Extract the content between []
    size_t startBracket = input.find('[');
    size_t endBracket = input.find(']');
    string innerContent = input.substr(startBracket + 1, endBracket - startBracket - 1);
    
    // Step 2: Replace ; with spaces and build the result
    for (char c : innerContent) {
        if (c == ';') {
            result += ' ';
        } else {
            result += c;
        }
    }
    
    return result;
}

int main() {
    string s1 = "[1 -2.5 3;4 5.25 6;7 8 9.12]";
    string processed = processNumericString(s1);
    cout << processed << endl; // Output: 1 -2.5 3 4 5.25 6 7 8 9.12
    return 0;
}

Approach 2: Use Regular Expressions (Cleaner, C++11+)

If you're using C++11 or later, regular expressions let you solve this in fewer lines by matching and replacing unwanted characters directly:

  1. First, remove all [ and ] from the string.
  2. Then replace every ; with a space.

Code Example:

#include <iostream>
#include <string>
#include <regex>
using namespace std;

string processWithRegex(const string& input) {
    // Remove brackets first
    regex bracketPattern(R"(\[|\])");
    string noBrackets = regex_replace(input, bracketPattern, "");
    
    // Replace semicolons with spaces
    regex semicolonPattern(R"(;)");
    return regex_replace(noBrackets, semicolonPattern, " ");
}

int main() {
    string s1 = "[1 -2.5 3;4 5.25 6;7 8 9.12]";
    string processed = processWithRegex(s1);
    cout << processed << endl;
    return 0;
}

Both approaches will give you the exact output you need, which you can then split into individual float values and store in an array (using stringstream for that next step, if you need it!).

内容的提问来源于stack exchange,提问作者Yusuf Sameh

火山引擎 最新活动