[英]Determining number of character in a string
好的,我想做的是找出輸入的單詞的長度是否可以被二整除。 如果是我想取中間兩個字符(比如說是Game,我想要'am')並將其添加到另一個單詞中。
import java.util.Scanner;
public class Assign33 {
public static void main(String[] args) {
System.out.println("Enter 3 words(Has to contain 4 letters)");
String word1;
String word2;
String word3;
Scanner in = new Scanner(System.in);
// Reads a single line word
// and stores into word variable
word1 = in.nextLine();
word2 = in.nextLine();
word3 = in.nextLine();
// gets each letter if the word has four letters
//this is the part I want to change
String sub0 = word1.substring(1,3)+word2.substring(1,3)+word3.substring( 1, 3 );
// Prints the new word
System.out.println("Can you pronounce: "+sub0);
}
}
如果要找出字符串的長度,請使用.length()
。 這應該可以幫助您找出單詞的中間位置。
如果您的輸入可以包含多個單詞,則從該行過濾第一個單詞。
word1 = word1.replaceAll(“ ^ \\ s *(\\ w +)\\ s *。* $”,“ $ 1”);
如果您的輸入只有一個單詞,則將其修剪。
word1 = word1.trim();
找到長度。
int length1 = word1.length();
如果我正確理解了您的問題,請執行以下操作:
String myWord = "Game";
String trimmedWord = myWord.trim();
int lengthOfWord = trimmedWord.length();
boolean lengthIsDivisibleByTwo = lengthOfWord%2 == 0;
String middleSection = "";
if (lengthIsDivisibleByTwo) {
int middleLetterIndex = lengthOfWord/2;
middleSection = trimmedWord.substring(middleLetterIndex-1, middleLetterIndex+1);
}
然后,“ middleSection”變量將保留您的“ am”或中間的2個字母。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.