簡體   English   中英

我如何使用循環而不是數組提取單詞

[英]How can i extract a word using loops and not arrays

情況:

用戶將輸入句子。 我需要對每個單詞進行某些修改,但要取決於每個單詞的長度。

例如,對於每個元音,如果單詞長度超過2,我需要在前面加上3。

// for words with length > 2
for (i=0;i<example.length();i++)

    switch (word.charAt(i))
    {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
    case 'y':
        output += "3" + word.charAt(i);
        break;
    default:
        output += word.charAt(i);
        break;
    }

目的:

在執行for循環之前,如何測試單詞的長度。 假設我的單詞長1個字符,我需要輸入一個“ 1”,2個字符長一個“ 2”。

例:

“你好,我叫羅傑”

輸出:

h3ell3o m2y n3am3e 2is 1A

重要:

沒有數組,僅用於while循環,switch或if語句。

public class Test {
  public static void main(String[] args) {
     String input = "hello my name is roger";
     input+=' '; // adding a whitespace at end to indicate completion of last word

     String word = "";
     char ch;
     String res = "";
     int len = input.length();

     for(int i = 0;i<len ;i++) {
       ch = input.charAt(i);
       if(Character.isWhitespace(ch)) {
         res = res +" "+processWord(word);
         System.out.println(word);
         word = "";
       }else {
         word+=ch;
       }
     }
}

  private static String processWord(String word) {
    // TODO Auto-generated method stub
    if(word.length()<=2) {
      return word;
    }

    // do whatever you have to do with your word
    String res = "";
    return res;
  }
}

基本上,提取單詞的邏輯是-

  1. 如果當前字符是空格,那么我們有一個單詞。
  2. 否則,如果當前字符不是空格,那么我們將該字符附加到正在構建的當前單詞上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM