字符串Awcing
1,字符數組輸入/輸出
char str[1000];
cin >>str;? //輸入字符串時,遇到空格或回車就會停止
scanf("%s",str)//輸入字符串時,遇到空格或回車就會停止
讀入一行字符串,包括空格
fgets(str,n,stdin)//str為數組名,n為要輸入多少個字符,? ? stdin以后解釋
cin.getline(a,n) //a為數組名,n為要讀入的字符數組長度
getline(cin,str)//str?必須是 string類型,即string str?這么定義
fgets函數及其用法,C語言fgets函數詳解_aa804738534的博客-CSDN博客_c語言fgets函數用法
cout <<str<<endl;
printf("%s",std);
puts(str);? //這個必須有頭文件? ? #include <cstring>.這個輸出也包括了換行符
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
char str1[1000];
int main(){cin >>str1;printf("下面是輸出:\n");puts(str1); printf("%s",str1);printf("%s",str1);return 0;
}下面是輸出:
abcd
abcdabcd
?2,字符串函數
頭文件:#include <cstring>
字典序比較方式:(ASCII碼依次比較)
3,其他
一個關于時間復雜度的問題?
我們遍歷整個字符串,使用 i<strlen(str)這個條件判斷
如果把長度計算好,i<len作為判斷條件?
?原因:strlen()函數,里面有循環語句, i<strlen(str)相當于雙重循環
一個關于過濾回車的問題(使用scanf會出現,cin沒有此問題)
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
char str1[100];
int main(){char str;scanf("%s",str1);scanf("%c",str);//再讀入一個字符 printf("str1:%s\n",str1);printf("str:%c",str); return 0;
}輸入:
abc
%
輸出:
str1:abc
str:
原因,str把我們的回車輸入進去了
解決:
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
char str1[100];
int main(){char str;scanf("%s",str1);getchar(); //過濾空格scanf("%c",&str);//再讀入一個字符 printf("str1:%s\n",str1);printf("str:%c",str); return 0;
}輸入:
abc
%
輸出:
str1:abc
str:%
4,string? ?
#include <string>
#include <cstdio>
#include <iostream>
#include <cctype>
//#include <bits/stdc++.h> 萬能頭文件,可以代替C++中大部分頭文件,所以可以把以上頭文件換成這一個
using namespace std;
int main(){string str;cin >>str;char c='A';cout <<str.substr(0,4)<<endl;//substr(i,len) i表示起始位置,len表示長度 cout <<str.substr(4)<<endl;//len 可勝率,則表示終止位置是結尾 cout <<str.find('p')<<endl;//從前往后尋找指定字符的下標位置 找到返回 第一個字符的索引沒找到返回 string::nposcout <<str.rfind('p')<<endl;//從后往前尋找指定字符的下標位置cout <<str.size()<<endl;//字符串長度(不包括'\0') cout <<str.empty()<<endl;//判斷是否為空字符串,是返回1,不是返回0 cout <<(char)towlower(c)<<endl;//#include <cctype> 轉化為小寫字母cout <<str.c_str();//.c_str() 相當于返回字符數組首地址 return 0;
}輸入:
philosophy
輸出:
phil
osophy
0
7
10
0
a
philosophy
#include<bits/stdc++.h>介紹_蔡尼瑪的博客-CSDN博客_#include<bits/stdc++.h>
tolower()函數_蔡尼瑪的博客-CSDN博客_tolower函數
printf函數輸出字符串是針對char *的,即printf只能輸出c語言的內置數據類型,而string不是c語言的內置數據類型。如需輸出string對象中的字符串,可以使用string的成員函數c_str(),該函數返回字符串的首字符的地址。
總結
- 上一篇: 白雪公主是谁写的呢?
- 下一篇: Awcing算法---区间合并