在一个字符串数组中,保存有十个人的名字,每个人的名字用英文的逗号分隔,现在要你找到李家的人,并把他们放入一个新的字符串中。
输入:"马云,李彦宏,李开复,刘强东,马化腾,古永锵,张朝阳,李思思,章泽天,马东敏"
输出:李彦宏,李开复,李思思
java算法
class FindNameLi { public static void main(String[] args) { String str = "马云,李彦宏,李开复,刘强东,马化腾,古永锵,张朝阳,李思思,章泽天,马东敏"; String newStr = ""; String str4Find = "李"; String endStr = ","; String[] ss = str.split(","); String temp = ""; for(int i = 0; i < ss.length; i++) { if(ss[i].startsWith(str4Find)) { temp += ss[i] + ","; } } //这里要截子串,然最后一个逗号给去掉 temp = temp.substring(0, temp.length() - 1); System.out.println(temp); } }
js算法:
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=gb2312"/> <title>test</title> <script type="text/javascript"> /*把遍历属性添加到数组的方法里面*/ Array.prototype.bianli = function() { for(var i = 0; i < this.length; i++) { document.writeln(this[i] + " "); } document.writeln("<br />"); } /*在下面这个数组中找出姓李的人*/ var str = "马云,李彦宏,李开复,刘强东,马化腾,古永锵,张朝阳,李思思,章泽天,马东敏"; var names = str.split(","); var newNames = ""; /*开始寻找姓李的人*/ for(var i = 0; i < names.length; i++) { if(isMr(names[i], "李")) { newNames += (names[i] + ","); } } /*截掉最后一个逗号*/ newNames = newNames.substr(0, newNames.length-1); names.bianli(); document.writeln(newNames); /*判断是否姓某某某,myName是传进来的名字,familyName是要找的姓名*/ function isMr(myName, familyName) { var c = myName.charAt(0); if(c == familyName) { return true; } return false; } </script> </head> <body> </body> </html>