【问题标题】:String to 2d Array字符串到二维数组
【发布时间】:2019-09-14 12:49:10
【问题描述】:

我想将字符串转换为二维数组。 但我的问题是字符串应该是动态的。 结果也应该是动态的。我尝试过使用队列,但我无法提出解决方案。

sentence = "这是一个例子。" 2DArray[][] = convertInto2dArray(句子)

二维数组应如下所示。 [[T][h][i][s],[i][s],[a][n],[e][x][a][m][p][l][e], [.]]

【问题讨论】:

  • 你想要这样的数组格式 [[["T"], ["h"], ["i"], ["s"]], [["i"], [" s"]], [["d"], ["y"], ["n"], ["a"], ["m"], ["i"], ["c"]], [ ["t"], ["e"], ["x"], ["t"]]]

标签: arrays string 2d converters


【解决方案1】:

在java中,多维数组只不过是数组的数组,所以用两个维数组[[T][h][i][s],[i][s],[a][n],[e][x][a][m][p][l][e],[.]]是不可能的。你应该有 3 个维度数组。

签出:https://www.baeldung.com/java-jagged-arrays

希望这能达到您的目的:

static char[][][] convert(String text) {
    String[] strSplit = text.split(" ");
    char[][][] out = new char[strSplit.length][][];

    for (int i = 0; i < strSplit.length; i++) {
        char[] word = strSplit[i].toCharArray();
        char[][] inner = new char[word.length][];
        for (int j = 0; j < word.length; j++) {
            inner[j] = new char[] { word[j] };
        }
        out[i] = inner;
    }
    return out;
}

输出:

[[[T], [h], [i], [s]], [[i], [s]], [[a], [n]], [[e], [x], [a], [m], [p], [l], [e], [.]]]

【讨论】:

    【解决方案2】:

    我是这样想的:

    def stringToArray(newstring):
        words = wordsandpoints(newstring)
    
    char newarray[wordsandpoints][]
        i=0
        row = 0
        for(;row < words;):
            for(int column=0;column < newstring.length(); column++, i++):
                if(newstring[i] =! " " or newstring[i] != ".")
                newarray[row][column] = newstring[i]
                elif(newstring[i] == ".")
                row++
                newarray[row][column] = newstring[i]
                row++
                else
                row++
    
    
        return newarray
    
    def wordsandpoints(b):
        i = 0
        for x in b:
            if(x == " ")
                i++
            elif(x == ".")
                i = i + 2
    
        return i
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 2020-09-02
      • 2020-09-15
      • 1970-01-01
      • 2016-05-06
      • 2019-01-23
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多