- 字符串刪除連續空格,只保留一個
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1;
char str2[100];
cout << "請輸入一個字符串:";
getline(cin, str1);//如果輸入有空格的字符串,用getline
int len = str1.size();//字符串的長度
int j = 0;
str2[0] = str1[0];
for (int i = 1; i < len; i++){//對字符串進行遍歷
if (str2[j] != str1[i]){
j++;
str2[j] = str1[i];
}
else if (str2[j] == str1[i] && str1[i] != ' '){
j++;
str2[j] = str1[i];
}
}
string end(str2, j+1);//最後將字符串賦值給string對象end 輸出
cout << end << endl;
while (1);
return 0;
}
2.刪除數中連續的數,保留一個數
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1;
char str2[100];
cout << "請輸入一個數:";
getline(cin, str1);//如果輸入有空格的字符串,用getline
int len = str1.size();//字符串的長度
int j = 0;
str2[0] = str1[0];
for (int i = 1; i < len; i++){//對字符串進行遍歷
if (str2[j] != str1[i]){
j++;
str2[j] = str1[i];
}
}
string end(str2, j+1);//最後將字符串賦值給string對象end 輸出
cout << end << endl;
while (1);
return 0;
}