簡體   English   中英

帶方法的反向字符串數組

[英]Reverse String Array w/Method

我需要使用靜態方法,該方法從相反的另一個字符串數組返回一個字符串數組。 因此,如果形式參數中的數組等於“ hello”,“有”,則返回值必須為“ olleh”,“ ereht”。

我的想法是使用charAt命令,但它似乎不適用於數組。 我無法使用內置方法一步解決此問題。 我也不知道如何繼續進行數組中的下一個元素。 這是我的代碼。

設置原始數組的main方法的一部分:

    String [] d = {"hey","hello"};
    System.out.println(Arrays.toString(count(d)));

我的方法:

    private static String [] count(String[] d)
{
    String[] reverse = new String [d.length];
    int l = d.length;
    for(int i = l -1; i >= 0; i--)
    {
        reverse = reverse + d.charAt(i);

    }
    return reverse;
}

因此,您想反轉數組中的每個字符串。

這是反轉單個字符串的一種方法:

private static String reverseString(String s) {
    char[] orig = s.toCharArray();
    char[] reverse = new char[orig.length];
    for (int i = 0; i < orig.length; i++) {    
        reverse[i] = orig[orig.length - i - 1];
    }
    return new String(reverse);
}

借助上述方法,您可以創建反向字符串數組,如下所示:

private static String[] reverseMany(String[] strings) {
    String[] result = new String[strings.length];
    for (int j = 0; j < strings.length; ++j) {
        result[j] = reverseString(strings[j]);
    }
    return result;
}

您可以使用StringBuilder#reverse反轉字符串。

以下代碼將反轉給定數組中的所有字符串:

private static String [] count(String[] d)
{
    String[] reverse = new String [d.length];
    for(int i = 0; i < d.length; i++)
    {
        reverse[i] = new StringBuilder(d[i]).reverse().toString();
    }
    return reverse;
}    

使用Java 8流的更優雅的單行解決方案是:

private static String [] count(String[] d)
{
    return Arrays.stream(d).map(s -> new StringBuilder(s).reverse().toString()).toArray(String[]::new);
}    

看看我用PHP創建的這段代碼,這很簡單:

// the array you want to reverse
$array = [13, 4, 5, 6, 40];
// get the size of the array
$arrayLength = count($array);
// get the index of the middle of the array
$index = intval($arrayLength / 2); 
for ($i=0; $i < $index; $i++) {
    // we store the value in a temp variable
    $tmp = $array[$i];
    // and finaly we switch values
    $array[$i] = $array[$arrayLength - $i - 1];
    $array[$arrayLength - $i - 1] = $tmp;
}

要在android中使用此庫,請編譯“ org.apache.commons:commons-lang3:3.5”

使用[Commons.Lang] [1],您可以簡單地使用

ArrayUtils.reverse(int[] array)

暫無
暫無

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

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