字符串操作
#include <bits/stdc++.h>
using namespace std;
string s;
int main(){
int cnt = 0;
while( cin >> s ){
cnt ++;
cout << "Case " << cnt << ":\n";
char tmp1,tmp2;
int i,j;
cin >> tmp1 >> i;
s.insert(s.begin()+i, tmp1);
cout << "Insert->" << s << endl;
cin >> tmp1; // 参数类型是迭代器,所以用remove获取迭代器位置
s.erase(remove(s.begin(), s.end(), tmp1), s.end());
cout << "Erase->" << s << endl;
cin >> tmp1 >> tmp2;
for (int i = 0; i < (int)s.length(); i++) {
if (s[i] == tmp1) {
s[i] = tmp2;
}
}
cout << "Replace->" << s << endl;
cout << "Size->" << s.length() << endl;
string reversedStr(s.rbegin(), s.rend());
cout << "Reverse->" << reversedStr << endl;
cin >> i >> j;
cout << "Sub->" << s.substr(i, j - i + 1) << endl;
string sub;
cin >> sub;
i = s.find(sub);
cout << "Find->" << i << endl;
cout << endl;
}
}
OJ不能用gets()
字符串替换
2.hashing strings
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str =null;
Map<String,String> map1 = new HashMap<String,String>();
Map<String,String> map2 = new HashMap<String,String>();
while(true) {
str = sc.nextLine();
if(str.equals("END")) {
break;
}
String[] spli = str.split(" ");
String tmp = spli[0];
String curse = tmp.substring(1, tmp.length()-1);
// 删除第一个和最后一个元素 只保留之间的
String effect = new String();
for(int i=1; i<spli.length; i++){
if( i==spli.length-1){
effect += spli[i];
}
else
effect += spli[i] + " ";
}
map1.put(curse, effect);
map2.put(effect, curse);
}
int n = sc.nextInt();
for(int i=0; i<n; i++) {
String s = sc.next();
s += sc.nextLine();
if(s.charAt(0)=='[') {
s = s.substring(1, s.length()-1);
if(map1.containsKey(s)) {
System.out.println(map1.get(s));
}else {
System.out.println("silence");
}
}else {
if(map2.containsKey(s)) {
System.out.println(map2.get(s));
}else {
System.out.println("silence");
}
}
}
}
}
trie字典树
#include <bits/stdc++.h>
using namespace std;
int main(){
char str[15];
map<string, int> m;
string tmp;
while(cin.getline(str,sizeof(str))){
int len = strlen(str);
if( len==0 )
break;
for(int i=len; i>0; i--){
str[i] = '\0';
// 将abandon abando aband aban aba ab a分别放进map
m[str]++;
// cout << m[str] << endl;
}
}
while(cin.getline(str,sizeof(str))){
if( m[str]>0 ){
printf("YES\n");
}
else{
printf("NO\n");
}
}
}