首頁  >  文章  >  如何將字串標記儲存到陣列中

如何將字串標記儲存到陣列中

王林
王林轉載
2024-02-09 13:30:151237瀏覽

php小編草莓將為大家介紹如何將字串標記儲存到陣列中。在程式設計過程中,我們經常需要處理字串並將其拆分成多個標記。將這些標記儲存到數組中可以方便我們處理和操作。本文將詳細說明如何使用php中的函數和方法來實現這項功能,幫助讀者更好地理解和運用。無論您是初學者還是有一定經驗的開發者,都可以從本文中獲得有益的知識和實用的技巧。讓我們一起開始吧!

問題內容

我參考了一些範例來成功提取使用者輸入的每個部分。但只能提取1次。應該有 2 個循環用於提取多個輸入並將標記保存在數組中。我被困在陣列上,我該怎麼辦?

question:
write a program that accepts string tokens in the format of token1:token2:token3:token4 , where : is used as delimiter to separate tokens. there should be two functions, ingest and appearance.

ingest takes a string, and stores it in the collection.

appearance takes a string as input . it returns a normalized value
between 0 to 1,  where the value represents the percentage of
appearances of stored tokens which have input as the prefix.

state the space and time complexity of your solution.


預期結果:

ingest('mcdonal:uk:employeea')
ingest('mcdonal:hk:employeea')
ingest('mcdonal:hk:employeeb')
ingest('mcdonal:hk:employeec')
ingest('fastfood')

appearance('mcdonal')
# > 0.8
appearance('mcdonal:hk')
# > 0.6

我的程式碼:

String input;
   
        
 // For user input
 Scanner sentense = new Scanner(System.in);
 input = sentense.nextLine();   
 String[] ingestWords = {};
       
             
 // Use ':' to seperate input
 StringTokenizer st = new StringTokenizer(input, ":");
 while(st.hasMoreTokens()) { 
   System.out.println(st.nextToken());
 }

解決方法

我建議您分兩步驟解決您的問題。

首先,攝取部分:您需要接受使用者輸入的單字,並將每個單字儲存在arraylist98c455a79ddfebb79781bff588e7b37e 中,而不是固定大小的陣列中,因為您事先不知道將獲得多少個輸入。

範例程式碼如下所示。

public static void main(string[] args) {
    string input;
    list<string> ingestwords = new arraylist<>();

    scanner sentence = new scanner(system.in);
        
    while (sentence.hasnext()) {
        input = sentence.next();
            
        if (input.equals("exit")) { // to stop receiving input
            break;
        }
            
        ingestwords.add(input);         
    }
    sentence.close();
}

第二,外觀部分:給定一個字串,您需要從攝取部分迭代單字列表,並檢查哪些單字以給定字串開頭。

例如,您可以建立一個像這樣的輔助函數。

void hasPrefix(String word, String str) {
    return word.startsWith(str);
}

將此函數應用於 ingestwords 中的每個單詞,將為您提供以 str 作為前綴的單字數。並且你可以從中算出出現的百分比。

以上是如何將字串標記儲存到陣列中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除