簡體   English   中英

將字符串中的每個字母加倍

[英]Doubling each letter in a String

我正在為Java 1做一個項目,而我完全陷入了這個問題。

基本上,我需要將字符串中的每個字母加倍。

"abc"  ->  "aabbcc"
"uk"   ->  "uukk"
"t"    ->  "tt"

我需要在while循環中完成值得考慮的“ Java 1”。 所以我猜測這意味着更多的問題方法。

我知道,據我所知,最簡單的方法是在while循環中使用charAt方法,但是由於某種原因,我無法確定如何將字符作為字符串返回給另一個方法。

謝謝

[編輯]我的代碼(錯誤,但這也許會有所幫助)

int index = 0;
  int length = str.length();
  while (index < length) {
      return str.charAt(index) + str.charAt(index);
      index++;
  }
String s="mystring".replaceAll(".", "$0$0");

方法String.replaceAll使用正則表達式語法,該語法Pattern文檔中進行了介紹,我們可以在其中學習. 匹配“任何字符”。 在替換中, $ number表示編號的“捕獲組”,而$0預定義為整個匹配項。 因此$0$0兩次引用匹配的字符。 顧名思義,該方法適用於所有匹配項,即所有字符。

是的,在這里for循環確實更有意義,但是如果您需要使用while循環,則它看起來像這樣:

String s = "abc";
String result = "";
int i = 0;
while (i < s.length()){
    char c = s.charAt(i);
    result = result + c + c;
    i++;
}

你可以做:

public void doubleString(String input) {

    String output = "";

    for (char c : input.toCharArray()) {
        output += c + c;
    }

    System.out.println(output);

}

您的直覺非常好。 charAt(i)將在位置i返回字符串中的字符,是嗎?

您還說過要使用循環。 遍歷列表長度string.length()for循環將允許您執行此操作。 在字符串中的每個節點上,您需要做什么? 字符加倍。

讓我們看一下您的代碼:

int index = 0;
int length = str.length();
while (index < length) {
    return str.charAt(index) + str.charAt(index);    //return ends the method
    index++;
}

對於您的代碼而言,問題在於,進入循環后,您將立即返回兩個字符。 因此,對於字符串abc ,您將返回aa 讓我們將aa存儲在內存中,然后返回完成的字符串,如下所示:

int index = 0;
int length = str.length();
String newString = "";
while (index < length) {
    newString += str.charAt(index) + str.charAt(index);
    index++;
}
return newString;

這會將字符添加到newString ,從而允許您返回完整的字符串,而不是單個雙精度字符集。

順便說一句,這可能更容易做為for循環,壓縮和澄清代碼。 我的個人解決方案(對於Java 1類)如下所示:

String newString = "";
for (int i = 0; i < str.length(); i++){
    newString += str.charAt(i) + str.charAt(i);
}
return newString;

希望這可以幫助。

嘗試這個

    String a = "abcd";
    char[] aa = new char[a.length() * 2];
    for(int i = 0, j = 0; j< a.length(); i+=2, j++){
        aa[i] = a.charAt(j);
        aa[i+1]= a.charAt(j);
    }
    System.out.println(aa);
public static char[] doubleChars(final char[] input) {
    final char[] output = new char[input.length * 2];
    for (int i = 0; i < input.length; i++) {
        output[i] = input[i];
        output[i + 1] = input[i];
    }
    return output;
}

假設這是在方法內部,則應該理解,您只能從方法中返回一次 遇到return語句后,控件將返回到calling方法 因此,您每次在循環中返回char的方法都是錯誤的。

int index = 0;
int length = str.length();
while (index < length) {
   return str.charAt(index) + str.charAt(index); // only the first return is reachable,other are not executed
   index++;
 }

更改方法以構建字符串並返回

public String modify(String str)
{
    int index = 0;
    int length = str.length();
    String result="";
    while (index < length) {
       result += str.charAt[index]+str.charAt[index];
       index++;
    }
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM