基本上,对于我分配的项目,我必须“ “通过检索每个句子的最后一个单词,删除除最后一个单词之外的所有标点符号来创建一个字符串,并输出这个新字符串”
我一直在检索最后一个单词,因为字符串内部有多个变量,这些变量会根据用户输入更改整个字符串的索引。
我尝试过使用索引并使用indexOf,但说实话,我碰壁了,完全陷入困境
String Sen1 = " There once was a person named " + firstName + " who lived in a city called " + city + ". ";
System.out.println("new phrase is: " + Sen1.substring(62, Sen1.length() - 2));
如果我严格使用我的个人信息,该代码将起作用。但如果另一个用户输入他们的信息,字符串的索引将会改变,并且打印结果将会错误。 我是否使用了正确的方法来解决此类问题? 有没有更简单的方法来实现这一点?
最佳答案
按空格分割输入字符串,并从结果字符串数组中返回最后一个字符串。 示例:
public static void main(String []args){
String variable = "randomlongwords";
String sentence = "Hello this is a " + variable + " random sentence. ";
String[] words = sentence.split(" ");
System.out.println(words[words.length - 1]);
}
输出:句子。
关于java - 我坚持尝试返回字符串的某个部分,因为它是一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838170/