[英]Simple Java Program to concat two strings with overlapping
我正在研究這個使用遺傳算法和蜂群優化開發混合算法的大學項目。 我被一個小問題困住了。
讓我們假設我們有兩個字符串:
String x="001100110011";
String y="001101110110";
我需要通過疊加它們來形成一個組合 x 和 y 的新字符串。
String out="001101110111";
我嘗試使用我在 StackOverflow 上找到的算法,但無法獲得所需的結果。
public String docat(String f, String s) {
if (!f.contains(s.substring(0,1)))
return f + s;
int idx = s.length();
try {
while (!f.endsWith(s.substring(0, idx--))) ;
} catch (Exception e) { }
return f + s.substring(idx + 1);
}
我的目標是繼續連接字符串,直到達到 111111111111。長度固定為 12。
public String doIt(String x, String y)
{
return Integer.toBinaryString(Integer.parseInt(x, 2) | Integer.parseInt(y, 2));
}
這適用於您的目標,並且主要與您的代碼有關。
(編輯:您可能需要格式化字符串以確保所有 12 位數字都在那里)
如果您的長度固定為 12,並且您所要做的就是對兩個字符串進行 OR 運算,那么只需執行以下操作:
String orStr (String s1, String s1)
{
String result = "";
for (int i=0; i<12; ++i)
{
if (s1.charAt(i)=='1' || s2.charAt(i)=='1')
{
result += "1";
} else {
result +="0";
}
}
return result;
}
但是為什么要在字符串中保留位呢?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.