【字符串、栈】单个char字符转为string表示

单个char转string

char x = 'a';
string c = string(1, x);

string转单个char

string s = "abc";
char x = s[0];

string转char[](字符数组)

string s = "abc";
s.c_str();

(字符数组)char[]转string

//直接赋值即可
char s1[4] = "abc";
string s2 = s1;

单个char转string例题

image

样例1
输入

{A3B1{C}3}3

输出

AAABCCCAAABCCCAAABCCC

说明:
(A3B1{C}3}3代表A字符重复3次, B字符重复1次,花括号中的C字符重复3次,最外层花括号中的AAABCCC重复3次。

C++代码

#include <iostream>
#include <stack>

using namespace std;
using i64 = long long;

const int N = 1e5 + 10;

stack<string> stk;

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    string s;
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        char x = s[i];
        string c = string(1, x);
        if (c == "{" || isalpha(x))
            stk.push(string(1, x));
        else if (isdigit(x))
        {
            int j = i, num = 0;
            while (j < s.size() && isdigit(s[j])) j++;
            num = stoi(s.substr(i, j - i));
            string tmp = stk.top();
            stk.pop();
            string t;
            for (int i = 0; i < num; i++) t += tmp;
            stk.push(t);
        }
        else if (c == "}")
        {
            string t;
            while (stk.size() && stk.top() != "{")
            {
                t = stk.top() + t;
                stk.pop();
            }
            stk.pop(); // 弹出左括号
            stk.push(t);
        }
    }
    string res;
    while (stk.size())
    {
        res = stk.top() + res;
        stk.pop();
    }
    cout << res;
    return 0;
}
posted @   Tshaxz  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
Language: HTML
点击右上角即可分享
微信分享提示