寻找子字符串/按行读文件
2020-03-21 本文已影响0人
迷糊银儿
- 问题一 from sg
其功能为从字符串str中返回从beginStr开始到endStr结束的中间子串。如str=”abcdefmsgleisw” beginStr=”cd” endStr=”ei” 结果为 “efmsgl“
public static String substr(String str, String begin, String end){
if(str.length()<=0){
return null;
}
int i= str.indexOf(begin);
//System.out.println(i);
int j= str.indexOf(end);
if(i==-1 || j==-1 || j<=i){ // begin/end不存在 || end在begin之前
return null;
}
i=i+begin.length();
return str.substring(i, j);
}
-
问题二 from sg
image.png
public static class Pro{
int count;
float price;
public Pro(int count,float price){
this.count=count;
this.price=price;
}
}
public static void getAvgPrice() throws Exception{
String path="log.txt";
HashMap<String,Pro> hashMap=new HashMap<>();
FileInputStream fileInputStream=new FileInputStream(path);
InputStreamReader in=new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bf=new BufferedReader(in);
try {
String content=bf.readLine();
while (content!=null){
float price=Float.parseFloat(content.split(" ")[4]);
String name=content.split(" ")[3];
if(hashMap.get(name)!=null){
hashMap.get(name).price+=price;
hashMap.get(name).count++;
}else if(hashMap.get(name)==null){
hashMap.put(name,new Pro(1,price));
}
content=bf.readLine();
}
for(String key:hashMap.keySet()){
System.out.println(key+" avg price is:"+hashMap.get(key).price/hashMap.get(key).count);
}
}catch (Exception e){
e.printStackTrace();
}finally {
fileInputStream.close();
in.close();
bf.close();
}
}
- 问题三 from ks
// 数组中每走m步,删除一个元素,数组走到最后则再回到数组首部,直到剩下最后一个元素输出;
public static void delItem(){
int[] arr={1,2,3,4,5,6};int m=2;
int len=arr.length;
//for(int i=0;i<len-1;i++){ //要找出len-1个元素,下标从0开始则i<len-1
int i=0;
int k=0;
int j=0;
while (i<len-1){
if(k==m){
arr[j%len]=-1;
i++;
k=0;
System.out.printf(j%len+"");
}
if(arr[(++j)%len]!=-1) {
k++;
}
}
System.out.printf("\n");
for (int f:arr){
System.out.println(f);
}
}