交叉合并:如字符串一为:abcd 字符串二为:1234
则结果为:a1b2c3d4
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class A { 5 public static void main(String[] args) { 6 String a[] ={"a","b","c"}; 7 String b[] ={"1","2","3"}; 8 CombineTwoArray(a, b); 9 System.out.println(CombineTwoArray(a, b)); 10 } 11 12 public static List<String> CombineTwoArray(String[] first, String[] second) { 13 List<String> outlist = new ArrayList<String>(); 14 int index = 0; 15 while (index < first.length && index < second.length) { 16 outlist.add(first[index]); 17 outlist.add(second[index]); 18 ++index; 19 } 20 if (index >= first.length) { 21 for (int i = index; i < second.length; i++) { 22 outlist.add(second[i]); 23 } 24 } else { 25 for (int i = index; i < first.length; i++) { 26 outlist.add(first[i]); 27 } 28 } 29 return outlist; 30 } 31 }
用js的写法:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>第十五题:交叉合并字符串</title> 5 <style> 6 #form{ 7 margin: 0 auto; 8 width:500px; 9 top:100px; 10 height:300px; 11 } 12 </style> 13 <script type="text/javascript"> 14 var reg = "^[A-Za-z0-9]+$"; 15 function check(){ 16 var str1 =document.all.str1.value; 17 var str2 =document.all.str2.value; 18 if(str1==""){ 19 alert("字符串一不允许为空!"); 20 document.all.str1.focus(); 21 return; 22 }else if(!/^[A-Za-z0-9]+$/.test(str1)){ 23 alert("字符串一只能是数字和字母的组合"); 24 document.all.str1.focus(); 25 return; 26 }else if(str2==""){ 27 alert("字符串二不允许为空!"); 28 document.all.str2.focus(); 29 return; 30 }else if(!/^[A-Za-z0-9]+$/.test(str2)){ 31 alert("字符串二只能是数字和字母的组合"); 32 document.all.str2.focus(); 33 return; 34 } 35 var string=""; 36 var font1 = "<font style='color:red;'>"; 37 var font2 = "<font style='color:blue;'>"; 38 var fontend = "</font>"; 39 if(str1.length>=str2.length){ 40 for(var i =0;i<str1.length;i++){ 41 if(i< str2.length){ 42 string += font1+str1[i]+fontend+ font2+ str2[i]+fontend; 43 }else{ 44 string += font1+str1[i]; 45 } 46 47 } 48 }else{ 49 for(var i =0;i<str2.length;i++){ 50 if(i< str1.length){ 51 string += font1+str1[i]+fontend + font2+str2[i]+fontend; 52 }else{ 53 string += font2+str2[i]+fontend; 54 } 55 56 } 57 } 58 document.all.result.innerHTML = string; 59 } 60 </script> 61 </head> 62 63 <body> 64 <div id="form"> 65 <center><h2>第十五题:交叉合并字符串</h2></center> 66 字符串1:<input type="text" id="str1"/><br/> 67 字符串2:<input type="text" id="str2"/><br/> 68 <input type="button" value="交叉合并字符串" onclick="check();"/> 69 <br /> 70 <div id="result"></div> 71 </div> 72 73 </body> 74 </html>
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/15787.html