搜尋
首頁Javajava教程在Java中列印字串的前K個字元的不同方法

在Java中列印字串的前K個字元的不同方法

A string is a class in Java that stores a series of characters enclosed within double quotes.Those characters are actually String-type objects. The string class is available in the'. ' package. Suppose we have given a string and a positive integer 'k'. Now, thejob is to print that string's first 'k' characters in Java. Also, check whether the length ofgiven string is less than or not, check whether the length ofgiven string is less than or not, if. the original string.

Java Program to Print First K Characters of the String

Let’s understand the given problem with a few examples −

實例

String st1 = “TutorialsPoint”;
String st2 = “Tutorial”;

假設我們已經有了上述字串,並且給定 k 值為 9。那麼,結果將會是 −

The first K characters of st1: Tutorials
The first K characters of st2: Tutorial

字串1的長度大於9,因此我們印了前9個字元。但是,字串2的長度小於9,因此我們印了整個字串本身

方法一

  • Create a user-defined method along with two parameters of String and integer type.

  • Convert the given string into a character array and store it in ‘chs[]’.

  • We know that strings are immutable in Java therefore we need to create an object ‘new_st’ of the StringBuffer class to store characters of string into a character array

  • 使用if-else區塊檢查字串的長度。如果長度大於k,則將前k個字元追加到字元陣列中,否則列印給定的陣列。

  • 現在,在main()方法中,宣告並初始化字串和一個正整數k。然後,使用字串和k作為參數呼叫使用者定義的方法

範例

以下範例說明如何使用使用者定義的方法來檢索字串的前K個字元。

import java.util.*;
public class Kstring {
   public static void frstChar(String st, int k) {
      char chs[] = st.toCharArray(); // converting into character array
      StringBuffer new_st = new StringBuffer();
      if(st.length() > k) { // checking the length of string
         for(int i = 0; i < k; i++) {
            new_st.append(chs[i]); // appending characters to new string
         }
         System.out.println("The first K characters are: " + new_st.toString()); // printing the new string
      } else {
         System.out.println("K is greater than given String: " + st);
      }
   }
   public static void main(String args[]) {
      String st1 = "TutorialsPoint";
      String st2 = "Tutorial";
      int k = 9;
      System.out.println("The Original String: " + st1);
      System.out.println("The Original String: " + st2);
      
      // calling the method
      frstChar(st1, k);
      frstChar(st2, k);
   }
}

Output

#
The Original String: TutorialsPoint
The Original String: Tutorial
The first K characters are: Tutorials
K is greater than given String: Tutorial

Approach 2

  • 宣告並初始化一個字串和一個正整數‘k’。

  • Now, using the if-else block check whether the length of String is greater than k or not. If it is greater than k, print the same number of characters of string using 'substring()' methoding(wisewise print the whole string.

  • #內建方法 'substring()' 接受兩個整數類型的參數,並列印指定字串中在參數範圍內的字元。

Example

The following example illustrates how we can retrieve the first K characters of a String using an in-built method ‘substring()’.

#
public class Kstring {
   public static void main(String args[]) {
      String st1 = "TutorialsPoint";
      int k = 9;
      System.out.println("The Original String: " + st1);
      
      if (st1.length() > k) { // checking the length of string
         System.out.println("The first K characters are: " + st1.substring(0, k));
      } else {
         System.out.println("The first K characters are: " + st1);
      }
   }
}

Output

#
The Original String: TutorialsPoint
The first K characters are: Tutorials

Conclusion

我們透過定義String並理解Java程式的問題陳述來開始本文。後來,我們討論了兩個範例程序,一個使用使用者定義的方法,另一個使用內建方法來列印給定String的前K個字元。

以上是在Java中列印字串的前K個字元的不同方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
說明JVM如何充當Java代碼和基礎操作系統之間的中介。說明JVM如何充當Java代碼和基礎操作系統之間的中介。Apr 29, 2025 am 12:23 AM

JVM的工作原理是將Java代碼轉換為機器碼並管理資源。 1)類加載:加載.class文件到內存。 2)運行時數據區:管理內存區域。 3)執行引擎:解釋或編譯執行字節碼。 4)本地方法接口:通過JNI與操作系統交互。

解釋Java虛擬機(JVM)在Java平台獨立性中的作用。解釋Java虛擬機(JVM)在Java平台獨立性中的作用。Apr 29, 2025 am 12:21 AM

JVM使Java實現跨平台運行。 1)JVM加載、驗證和執行字節碼。 2)JVM的工作包括類加載、字節碼驗證、解釋執行和內存管理。 3)JVM支持高級功能如動態類加載和反射。

您將採取哪些步驟來確保Java應用程序在不同的操作系統上正確運行?您將採取哪些步驟來確保Java應用程序在不同的操作系統上正確運行?Apr 29, 2025 am 12:11 AM

Java應用可通過以下步驟在不同操作系統上運行:1)使用File或Paths類處理文件路徑;2)通過System.getenv()設置和獲取環境變量;3)利用Maven或Gradle管理依賴並測試。 Java的跨平台能力依賴於JVM的抽象層,但仍需手動處理某些操作系統特定的功能。

Java是否需要特定於平台的配置或調整區域?Java是否需要特定於平台的配置或調整區域?Apr 29, 2025 am 12:11 AM

Java在不同平台上需要進行特定配置和調優。 1)調整JVM參數,如-Xms和-Xmx設置堆大小。 2)選擇合適的垃圾回收策略,如ParallelGC或G1GC。 3)配置Native庫以適應不同平台,這些措施能讓Java應用在各種環境中發揮最佳性能。

哪些工具或庫可以幫助您解決Java開發中特定於平台的挑戰?哪些工具或庫可以幫助您解決Java開發中特定於平台的挑戰?Apr 29, 2025 am 12:01 AM

Osgi,Apachecommonslang,JNA和JvMoptionsareeForhandlingForhandlingPlatform-specificchallengesinjava.1)osgimanagesdeppedendendencenciesandisolatescomponents.2)apachecommonslangprovidesitorityfunctions.3)

JVM如何在不同平台上管理垃圾收集?JVM如何在不同平台上管理垃圾收集?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

為什麼Java代碼可以在不同的操作系統上運行,而無需修改?為什麼Java代碼可以在不同的操作系統上運行,而無需修改?Apr 28, 2025 am 12:14 AM

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

描述編譯和執行Java程序的過程,突出平台獨立性。描述編譯和執行Java程序的過程,突出平台獨立性。Apr 28, 2025 am 12:08 AM

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具