如何將字串標記儲存到陣列中
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()); }
登入後複製
解決方法
我建議您分兩步驟解決您的問題。
首先,攝取部分:您需要接受使用者輸入的單字,並將每個單字儲存在arraylist<string>
中,而不是固定大小的陣列中,因為您事先不知道將獲得多少個輸入。
範例程式碼如下所示。
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中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
Windows 11 KB5054979中的新功能以及如何解決更新問題
3 週前
By DDD
如何修復KB5055523無法在Windows 11中安裝?
2 週前
By DDD
Inzoi:如何申請學校和大學
4 週前
By DDD
如何修復KB5055518無法在Windows 10中安裝?
2 週前
By DDD
Roblox:Dead Rails - 如何召喚和擊敗Nikola Tesla
4 週前
By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)