统计数组每个索引中','之前的字符数,并返回最高的

Counting characters before a ',' in each index of array, and returning the highest

我需要从这个数组中获取最长的姓氏 return 它。

String[] names = {"Turner, Brendan", "Savage, Fred", "Zidy, Boop",
                 "Zobie, Brendan", "Flurb, Fred", "Mopeeeeeyyy, Boopertinson"};

到目前为止我有这个;

public static void getLongestSurname(String[] name){
         int i = 0;
         int x = 0;
         int currentLength = 0; 
         int lastLength = 0; 
         String longestName = null;
    for(int j = 0; j < (name.length); j++){
      
          while (name[j].charAt(i) != ',') {
          i++;
          currentLength++;
          }
      System.out.println(i);
      System.out.println("current is"+currentLength);
      i = 0;
      currentLength = 0;
        if ( currentLength > lastLength ){
           longestName = name[i]; 
          }
    }
    
     System.out.println("longest surname should be; "+ longestName);
  }

但它给出的输出是“最长的姓氏应该是;Turner, Brendan” 这不是列表中最长的名字。

我在这里做错了什么,但此时我的大脑感觉像炒鸡蛋。有人可以帮忙吗?

谢谢。

您需要在迭代所有名称时跟踪 longestName,将当前名称的长度与当前名称的长度 longestString 进行比较,而不是与 lastLength

进行比较

如果 currentName 的长度大于 longestNumber 的长度,longestName 将被更新

解决方案

public static void getLongestSurname(String[] name){
        
        int currentLength = 0; 
        int lastLength = 0; 
        String longestName = null;
        for(int j = 0; j < (name.length); j++){

           // split string by "," to get surname
            String[] strAr = name[j].split(",");
            // length of current surname 
            currentLength = strAr[0].length();
           // compare length of current surname with longest surName                
            if ( currentLength > lastLength ){
                longestName = name[j]; 
                lastLength = strAr[0].length();
            }
        }

        System.out.println("longest surname should be; "+ longestName);
    }

对于数组中的每个名字,解析姓氏。将其与当前最长的姓氏进行比较。如果电流为空或更短,则更换它。继续这样做,直到列表用完。 Return结果。

public String findLongestSurname(String[] names) {
  String longestSurname = null;
  for (String name : names) {
    String[] tokens = name.split(",");
    String surname = tokens[0];
    if (longestSurname == null || surname.length > longestSurname.length) {
      longestSurname = surname;
    }
  }
  return longestSurname;
}