|
发表于 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;
}
|
|