Java程式:刪除指定位置的字元
在本文中,我們將學習如何使用Java從字串中刪除指定位置的字元。我們將使用substring() 方法來實現這一點,方法是將字串分割成要刪除字元之前和之後的兩部分,然後將這兩部分組合起來。
問題陳述
編寫一個Java程式來刪除指定位置的字元。
輸入
The Haunting of Hill House!
輸出
String after removing a character: The Hauting of Hill House!
刪除指定位置字元的步驟
以下是刪除指定位置字元的步驟:
- 定義字串並指定要刪除的字元的位置。
- 使用substring() 方法獲取字串在指定位置之前和之後的部分。
- 組合這兩部分以獲得最終字串。
- 列印修改後的字串。
Java程式:刪除指定位置的字元
以下是完整的示例及其輸出:
public class Demo {
public static void main(String[] args) {
String str = "The Haunting of Hill House!";
System.out.println("String: "+str);
// removing character at position 7
int pos = 7;
String res = str.substring(0, pos) + str.substring(pos + 1);
System.out.println("String after removing a character: "+res);
}
}
輸出
String: The Haunting of Hill House! String after removing a character: The Hauting of Hill House!
程式碼解釋
要刪除指定位置的字元,我們使用以下邏輯:
假設我們的字串如下所示。
String str = "The Haunting of Hill House!";
我們想刪除位置7的字元。為此,請使用以下邏輯。
// removing character at position 7 int pos = 7; String res = str.substring(0, pos) + str.substring(pos + 1);
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP