字符串的題目一直做不好,一些知識點掌握不熟練。在1019的坑裏繞了一天,終於AC!
整理一下關於字符串的點~~(持續更新)
一、輸入問題
1,最簡單的一種:事先輸入n,規定了用例組數;輸入字符串中間沒有空格或者空格是可預知的。這時對字符串通常用字符數組char [],操作比string類型方便:
int n;
cin >> n;
while(n--){
char str[N] = " "; //最好初始化,否則循環時可能對以後的數據有影響,不知道爲什麼
cin >> str;
}
比如九度1013,開門人關門人,輸入爲
EE301218 08:05:35 20:56:352,輸入多組字符串,輸入字符串中間有空格,直到遇到規定結尾。這時不能用字符數組char [],只能用string 和getline:
string str;
while(getline(cin, str)){
if(str == "規定結尾") break;
}
比如1019,簡單計算器,輸入爲
1 + 2 4 + 2 * 5 - 7 / 11 0
3,其他,不是正常情況,只列出代碼和運行結果:
int main(){
char str[N];
while(scanf(" %s", str) != EOF){
cout << str;
}
return 0;
}
結果:
輸入:12 34 hhh aaa, b
輸出:1234hhhaaa,b
二、字符數組char []常用方法
1,長度 strlen(str)
三、字符串string常用方法
1,長度 str.size()或str.length()
四、vector<type>常用方法
1,添加到末尾str.push_back()
2,彈出末尾元素str.pop_back()
3,清空str.clear()
五、字符和數字轉化(整型或浮點型)
字符轉數字
1,單個數字:str[i] - '0'
2,字符串(參數爲const char *,不能是string哦):atoi(str)(頭文件<stdlib.h>)
數字轉字符
3,snprintf(str, "%d", 123)
六、切分,以空格或其他字符(可以多個)切分字符串,並加入vector<string>
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#define N 100
using namespace std;
int main(){
string str;
char str0[N];
vector<string> ans;
getline(cin, str);
for(int i = 0; i < str.size(); i++){
str0[i] = str[i];
}
char *sep = " "; //如果以多個符號切分,直接加入即可,如",+"
char *p;
p = strtok(str0, sep); //char * strtok(char *s, const char *delim)
while(p){
ans.push_back(p);
p = strtok(NULL, sep);//strtok固定用法,第一次p = strtok(str0, sep);第二次 p = strtok(NULL, sep);
}
for(int i = 0; i < ans.size(); i++){
cout << "ans[" << i << "] = " << ans[i] << endl;
}
return 0;
}
結果:
輸入:abc de 123
輸出:
ans[0] = abc
ans[1] = de
ans[2] = 123
最後,貼一下1019的題目和自己的做法,已AC,歡迎批評指正~
- 題目描述:
-
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
- 輸入:
-
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
- 輸出:
-
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
- 樣例輸入:
-
1 + 2 4 + 2 * 5 - 7 / 11 0
- 樣例輸出:
-
3.00 13.36
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <stdlib.h>
#define N 201
using namespace std;
main(){
string str;
while(getline(cin, str)){
if(str == "0") break;
char str0[N] = " ";
for(int i = 0; i < str.size(); i++){ //將string轉移到char[]中
str0[i] = str[i];
}
vector<double> num; //num中存放數字
vector<char> sf; //sf中存放+、-號, * 和 / 在遍歷時就直接計算出來
double ans;
double a, b;
char *sep = " "; //以空格切分字符串,同時計算乘除
char *p;
p = strtok(str0, sep);
while(p){
if(p[0] == '+' || p[0] == '-'){
sf.push_back(p[0]);
}else if(strcmp(p, "*") == 0){
a = num[num.size() - 1];
num.pop_back();
p = strtok(NULL, sep);
num.push_back(a * atof(p));
}else if(strcmp(p, "/") == 0){
a = num[num.size() - 1];
num.pop_back();
p = strtok(NULL, sep);
num.push_back(a / atof(p));
}else{
num.push_back(atof(p));
}
p = strtok(NULL, sep);
}
ans = num[0];
int k = 0;
for(int i = 1; i < num.size(); i++){ //再遍歷num和sf,此時只要順序計算加減法
if(sf[k] == '+'){
ans = ans + num[i];
}else if(sf[k] == '-'){
ans = ans - num[i];
}
k++;
}
printf("%.2f\n", ans);
}
return 0;
}