ในบทความนี้ เราจะเข้าใจวิธีรับอักขระจากสตริงที่กำหนด Char เป็นประเภทข้อมูลที่มีตัวอักษรหรือจำนวนเต็มหรืออักขระพิเศษ สตริงเป็นประเภทข้อมูลที่มีอักขระตั้งแต่หนึ่งตัวขึ้นไปและอยู่ในเครื่องหมายคำพูดคู่ (“ ”)
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Input string: Java Programming Index: 11
ผลลัพธ์ที่ต้องการจะเป็น −
Result: m
อัลกอริทึม
Step 1 - START Step 2 - Declare a string value namely input_string and a char value namely resultant_character. Step 3 - Define the values. Step 4 - Using the function string.charAt(), fetch the char value present at the specified position. Store the value in resultant_character. Step 5 - Display the result Step 6 - Stop
ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
public class CharacterAndString {
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " +string);
int index = 11;
char resultant_character = string.charAt(index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
} ผลลัพธ์
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
public class CharacterAndString {
public static char get_chararacter(String string, int index) {
return string.charAt(index);
}
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " +string);
int index = 11;
char resultant_character = get_chararacter(string, index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
} ผลลัพธ์
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m