在Java中提取字符串最后一个字符可以通过多种方法实现。首先,可以使用lastIndexOf()方法来找到最后一个字符的位置。接着,使用substring()方法来提取该位置及其后的字符。
具体实现步骤如下:假设有一个字符串s,其内容为"Create a new class named Sentence.java. In the main method, write a program that reads a sentence using a dialog box. Depending on the last character of the sentence, output another dialog box identifying the sentence as declarative (ends with a period), interrogative (ends with a question mark), exclamatory (ends with an exclamation point), or other. Use a switch structure to accomplish this."。要获取句子的最后一个标点符号,可以采用以下方式:
1. 使用lastIndexOf()方法找到最后一个标点符号的位置。例如,若要获取最后一个句点的位置,可以这样写:
int index = s.lastIndexOf(".");
2. 使用substring()方法从找到的位置开始提取到最后。代码如下:
String ss = s.substring(index, s.length());
3. 如果只想获取最后一个字符,可以简化为:
String ss = s.substring(s.length() - 1);
这样,ss就保存了最后一个字符,即标点符号。
需要注意的是,这里的索引是从0开始的,因此使用s.length() - 1可以确保获取到最后一个字符。
总结来说,通过合理使用lastIndexOf()和substring()方法,可以轻松实现从字符串中提取最后一个字符的目的。
温馨提示:答案为网友推荐,仅供参考