VC驿站

 找回密码
 加入驿站

QQ登录

只需一步,快速开始

搜索
查看: 1050|回复: 2

求一个算法

[复制链接]
41_avatar_middle
最佳答案
0 
在线会员 发表于 2023-2-3 20:17:17 | 显示全部楼层 |阅读模式
本帖最后由 sbw 于 2023-2-3 21:29 编辑

循环读取字符串(或是字符串组),如果前后或中间有空格删除,
判断字符串长度,如果不足10个,从后面加 0 补足10个
如果大于10个 从后取10位 赋值到新串
求一个算法




上一篇:老师封装的CTabSheet 类使用Tab控件中出现的问题
下一篇:求解决FindNextFile函数执行失败问题 错误码122
71_avatar_middle
最佳答案
2 
在线会员 发表于 2023-2-28 23:10:19 | 显示全部楼层
用C++编写的示例代码,用于循环读取字符串数组,删除前后和中间的空格,并根据需要在字符串的末尾添加零或缩短字符串长度:
#include <iostream>
#include <string>

using namespace std;

int main() {
    string inputString;
    cout << "Please enter a string: ";
    getline(cin, inputString);
   
    while (inputString != "exit") {
        // Remove spaces at the beginning and end of the string
        inputString.erase(0, inputString.find_first_not_of(" "));
        inputString.erase(inputString.find_last_not_of(" ") + 1);

        // Remove spaces in the middle of the string
        for (int i = 0; i < inputString.length(); i++) {
            if (inputString[i] == ' ' && inputString[i + 1] == ' ') {
                inputString.erase(i, 1);
                i--;
            }
        }

        // Check the length of the string and add zeros if necessary
        if (inputString.length() < 10) {
            inputString.append(10 - inputString.length(), '0');
        }
        else if (inputString.length() > 10) {
            inputString = inputString.substr(inputString.length() - 10);
        }

        // Output the modified string
        cout << "Modified string: " << inputString << endl;

        // Read the next input string
        cout << "Please enter another string (or 'exit' to quit): ";
        getline(cin, inputString);
    }

    return 0;
}
71_avatar_middle
最佳答案
2 
在线会员 发表于 2023-2-28 23:11:25 | 显示全部楼层
在这个示例代码中,使用了C++ STL中的string类来处理字符串。在循环中,首先从用户输入中读取一个字符串。然后使用erase函数从字符串的开头和结尾删除所有的空格。接下来,使用一个循环来删除字符串中间的多余空格。然后,检查字符串的长度,并在末尾添加零或缩短字符串的长度。最后,输出修改后的字符串,并继续读取下一个输入字符串,直到用户输入"exit"为止。
您需要登录后才可以回帖 登录 | 加入驿站 qq_login

本版积分规则

×【发帖 友情提示】
1、请回复有意义的内容,请勿恶意灌水;
2、纯数字、字母、表情等无意义的内容系统将自动删除;
3、若正常回复后帖子被自动删除,为系统误删的情况,请重新回复其他正常内容或等待管理员审核通过后会自动发布;
4、感谢您对VC驿站一如既往的支持,谢谢合作!

关闭

站长提醒上一条 /2 下一条

QQ|小黑屋|手机版|VC驿站 ( 辽ICP备09019393号-4 )|网站地图wx_jqr

GMT+8, 2023-12-8 18:50

Powered by CcTry.CoM

© 2009-2021 cctry.com

快速回复 返回顶部 返回列表