【问题标题】:Get each character from each string by column按列从每个字符串中获取每个字符
【发布时间】:2018-12-22 10:26:43
【问题描述】:

我一直在尝试按列从每个字符串中获取每个字符,但我只得到每个字符串的第一个字符,我想从每个字符串中逐列获取每个字符。

例如:

我有来自 ArrayList of Strings 的三个字符串:

  1. ut

我想发生的事情一定是这样,从字符串中逐列获取每个字符后:

  1. 俱乐部
  2. hlt
  3. io

这么久了,我当前的源代码只获取前两个字符串的第一个字符,即'cl',这是我当前的源代码:

List<String> New_Strings = new ArrayList<String>();
int Column_Place = 0;
for (String temp_str : Strings) {
    try{ //For StringIndexOutOfBoundsException (handle last String)
        if(Column_Place >= temp_str.length()){
            Current_Character = temp_str.charAt(Column_Place);
            New_Strings.add(Character.toString(Current_Character));
            break;
        }else if (Column_Place < temp_str.length()){
            Current_Character = temp_str.charAt(Column_Place);
            New_Strings.add(Character.toString(Current_Character));
        }
    }catch(Exception e){
        continue;
    }
    Column_Place++;
}

【问题讨论】:

  • 您还需要分享您是如何声明这些变量的。还请遵循 java 命名约定。您的代码几乎无法阅读。
  • 我不同意说代码“几乎无法阅读”的帖子;确实,以小写字母开头的变量名称是几乎所有地方都遵循的强约定。我在代码中看到的最大问题是我们不知道New_Strings 是如何声明的。它似乎是某种字符串列表,但会为每个源字符串中的每个字母获取一个新字符串,这与所需的输出不匹配。我认为你想要的是一个字符串列表,并将列 N 中的每个字符附加到字符串 N,但我不确定。

标签: java string algorithm loops loop-invariant


【解决方案1】:

您正在将单个字符的字符串表示形式添加到结果字符串中。相反,您应该将这些字符累积到结果字符串中。例如:

int numStrings = strings.size();
List<String> result = new ArrayList<>(numStrings);
for (int i = 0; i < numStrings; ++i) {
    StringBuilder sb = new StringBuilder();
    for (String s : strings) {
        if (i < s.length) {
            sb.append(s.charAt(i));
        }
    }
    result.add(sb.toString());
}

【讨论】:

  • 我将 for 循环条件更改为 i
【解决方案2】:

只需调用 groupByColumn(Arrays.asList("chi", "llo", "ut"):

public static List<String> groupByColumn(List<String> words) {
    if (words == null || words.isEmpty()) {
        return Collections.emptyList();
    }

    return IntStream.range(0, longestWordLength(words))
            .mapToObj(ind -> extractColumn(words, ind))
            .collect(toList());

}

public static String extractColumn(List<String> words, int columnInd) {
    return words.stream()
            .filter(word -> word.length() > columnInd)
            .map(word -> String.valueOf(word.charAt(columnInd)))
            .collect(Collectors.joining(""));
}

public static int longestWordLength(List<String> words) {
    String longestWord = Collections.max(words, Comparator.comparing(String::length));
    return longestWord.length();
}

【讨论】:

    【解决方案3】:

    您使用增强的/foreach 循环对列表进行迭代。 因此,您将在每个上迭代一次 细绳。而您的结果:仅处理第一个字母。
    您应该使用while 循环和while 条件while(Column_Place &lt; Strings.size()) 这样的方法。
    或者作为替代方案,您可以分两个不同的步骤执行操作并使用 Java 8 功能。

    请注意,在 Java 中,变量以小写字母开头。请遵循约定,以使您的代码在此处和那里更具可读性/可理解性。

    在 Java 8 中你可以这样做:

    List<String> strings = new ArrayList<>(Arrays.asList("chi", "llo", "ut"));
    
    int maxColumn = strings.stream()
                     .mapToInt(String::length)
                     .max()
                     .getAsInt(); // suppose that you have at least one element in the List
    
    
    List<String> values =
            // stream from 0 the max number of column
            IntStream.range(0, maxColumn) 
                     // for each column index : create the string by joining their 
                     // String value or "" if index out of bound
                     .mapToObj(i -> strings.stream() 
                                           .map(s -> i < s.length() ? String.valueOf(
                                                   s.charAt(i)) : "")
                                           .collect(Collectors.joining()))
                     .collect(Collectors.toList());
    

    【讨论】:

      【解决方案4】:

      只需将列表视为二维数组。从列表中拆分每个项目,从每个项目中获取第 j 个字符,当且仅当项目的长度大于索引 j。

          ArrayList<String> list = new ArrayList<String>();
          list.add("chi");
          list.add("llo");
          list.add("ut");
      
      
          int size = list.size();
          int i=0, j=0,k=0;
          while(size-- > 0){
              for(i=0; i<list.size(); i++){
                  String temp = list.get(i);
                  if(j < temp.length()){
                      System.out.print(temp.charAt(j));
                  }
              }
              j++;
              System.out.println();
          }
      

      【讨论】:

        猜你喜欢
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多