【问题标题】:How to find the last character in a String?如何找到字符串中的最后一个字符?
【发布时间】:2017-11-12 17:17:36
【问题描述】:

有一个巨大的字符串数组,我必须遍历字符串数组,看看哪些单词有一定的长度(qualifyingLenght),它应该以Task 3的字符a结尾。

我真的很努力,但无法弄清楚。 TIA。

package set07110;
/**
 * A String array defined as a static instance variable called data;
 */
public static String[] data = { "Achelous", "Ares", "Clytemnestra", "Eurystheus", "Icarus", "Naiads", "Phlegethon", "Sterope",
        "Acheron", "Argo", "Cocytus", "Euterpe", "Io", "Napaeae", "Phosphor", "Stheno", "Achilles", "Argus", };



public static void main(String[] args) { //Print the only two character name


    System.out.println("Task 1");
    System.out.println("Enter Length: ");
    Scanner scan = new Scanner(System.in);
    int qualifyingLength = scan.nextInt();

    for(String string: data) {

        if(!(qualifyingLength == string.length())) {
            System.out.println("Try again");
        }
        else if (qualifyingLength == string.length()) {
            System.out.println("The words are: " + string);
        }
    }
    System.out.println("Task 2");
    int count = 0; //Identify the three characters where the name ends with "seus"
    for (int index = 0; index < data.length; index++) { {
        if (data[index].contains("seus")) {
            count++;
            boolean seus = data[index].contains("seus");
            System.out.println("The words containing seus: " + data[index]);
        }

    }


    }
    //Print the names with 9 letter that end in "a".
    System.out.println("Task 3");
    System.out.println("Enter Length: ");
    int qualifyingLength1 = scan.nextInt();  // enter a number which indicates how much letter
    // do we want in a word
    for(String string: data) {
        int lastChar = (data.length - 1);
        boolean startsWithA = data.charAt(lastChar) == 'a'; //(have to find the last character in a Array of Strings
        // and see if the word ends with the character "a" --> (doesn't work)
        if(qualifyingLength1 == string.length() ) {
            System.out.println("The words are: " + string);
        }

    }
}

【问题讨论】:

  • 使用endsWith(..) 方法怎么样?见官方javadoc
  • “代码很大” - 所以发布minimal reproducible example。发布一个甚至没有显示 data 是什么的 sn-p 并没有多大帮助。 (您不需要使用扫描仪或任何东西 - 一个简单的控制台应用程序,它创建一个硬编码的字符串数组,然后尝试从每个字符串中打印出最后一个字符就可以了。)但目前@987654330 @ 是data 中的最后一个索引,而不是string 中的最后一个字符。
  • @zefixlluja 哦,对了,谢谢
  • @JonSkeet 我会记住这一点,谢谢
  • 与其只是“牢记在心”,为什么不编辑您的问题以改进它呢? Stack Overflow 旨在成为一个很好的问题和答案的存储库 - 我敦促您改进您的问题。见codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question

标签: java arrays string eclipse char


【解决方案1】:

先检查之前的长度,然后简单地使用endsWith作为

for(String string: data) {
    if(qualifyingLength1 == string.length() && string.endsWith("a") )      
       // got your input
    // else {continue;} //optional
}

【讨论】:

  • 天哪,谢谢。不敢相信我居然想不通
  • @Midnight 我很高兴能帮上忙 :)
猜你喜欢
  • 2020-03-13
  • 1970-01-01
  • 2022-06-17
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 2020-03-12
相关资源
最近更新 更多