1

这是整个问题的SS。http://prntscr.com/1dkn2e 它应该适用于任何句子,而不仅仅是示例中给出的那个我知道它必须对字符串做一些事情。我们的教授已经使用了这些字符串方法 http://prntscr.com/1dknco

这只是一个基本的java类,所以不要使用任何复杂的东西,这就是我所拥有的,不知道在此之后该怎么做任何帮助将不胜感激。

 public static void main(String[] args)
 {
      Scanner keyboard = new Scanner(System.in);    
      System.out.println("Enter a line of text. No punctuaton please");
      String sentence = keyboard.nextLine();
      System.out.println(sentence);
    }
}
4

4 回答 4

2

您可以使用public String[] split(String regex)

splitted = sentence.split("\\s+"); 
  • splitted[0]是第一个字。
  • splitted[splitted.length - 1]是最后一句话。

由于您不允许使用String#split,因此您可以执行以下操作:

myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord; 

通过这样做,您将拥有一个包含没有最后一个单词的句子的子字符串。(要提取第一个单词,您可以使用String#indexOf

firstWord是您之前提取的第一个单词(我不会为您解决整个问题,尝试自己做,现在应该很容易)

于 2013-07-04T20:53:40.683 回答
0

好吧,您似乎正在寻找非常简单的字符串算术。所以这是我能做的最简单的事情:

      // get the index of the start of the second word
      int index = line.indexOf (' ');
      // get the first char of the second word
      char c = line.charAt(index+1);
      /* this is a bit ugly, yet necessary in order to convert the
       * first char to upper case */
      String start = String.valueOf(c).toUpperCase(); 
      // adding the rest of the sentence
      start += line.substring (index+2);
      // adding space to this string because we cut it
      start += " ";
      // getting the first word of the setence
      String end = line.substring (0 , index);
      // print the string
      System.out.println(start  + end);
于 2013-07-04T21:20:50.643 回答
0

试试这个

String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
于 2013-07-04T21:21:16.120 回答
-1

这是您可以执行此操作的另一种方法。更新:没有循环

              Scanner keyboard = new Scanner(System.in);    
      System.out.println("Enter a line of text. No punctuaton please");
      String sentence = keyboard.nextLine();
      System.out.println(sentence);
      int spacePosition = sentence.indexOf(" ");
      String firstString = sentence.substring(0, spacePosition).trim();
      String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
      String firstChar = restOfSentence.substring(0, 1);
      firstChar = firstChar.toUpperCase();
      restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
      System.out.println(restOfSentence + " " + firstString);
      keyboard.close();
于 2013-07-04T21:49:48.767 回答