Strings (Strings)
Strings: کار با متن 📝
String ها یکی از پرکاربردترین انواع داده هستن. Kotlin قابلیتهای عالی برای کار با String داره!
String Interpolation (قالببندی):
یکی از بهترین ویژگیهای Kotlin! میتونید متغیرها رو مستقیماً در String استفاده کنید:
val name = "Ali"
val age = 25
// String interpolation
val message = "My name is $name and I'm $age years old"
println(message) // My name is Ali and I'm 25 years old
// Expression در interpolation
val info = "Next year I'll be ${age + 1} years old"
// Property access
val length = "The length is ${name.length}"
تفاوت $ و ${}:
$variable برای متغیرها و ${expression} برای expression ها استفاده میشه.
Multi-line Strings:
// Triple-quoted string
val text = """
Line 1
Line 2
Line 3
""".trimIndent()
// یا با trimMargin
val text2 = """
|Line 1
|Line 2
""".trimMargin("|")
String Functions:
val text = "Hello, Kotlin!"
// تغییر case
text.uppercase() // "HELLO, KOTLIN!"
text.lowercase() // "hello, kotlin!"
text.capitalize() // "Hello, kotlin!"
// بررسی
text.contains("Kotlin") // true
text.startsWith("Hello") // true
text.endsWith("!") // true
// تقسیم و اتصال
val parts = text.split(", ") // ["Hello", "Kotlin!"]
val joined = parts.joinToString(" - ") // "Hello - Kotlin!"
// جایگزینی
text.replace("Kotlin", "World") // "Hello, World!"
// طول و خالی بودن
text.length // 17
text.isEmpty() // false
text.isBlank() // false (فقط whitespace)
مثال عملی: فرمتبندی پیام
fun greetUser(name: String, age: Int, isVip: Boolean) {
val status = if (isVip) "VIP" else "Regular"
val message = """
Welcome, $name!
Age: $age
Status: $status
${if (isVip) "🎉 Special benefits for you!" else ""}
""".trimIndent()
println(message)
}
greetUser("Ali", 25, true)
Raw Strings: Triple-quoted strings میتونن هر کاراکتری رو شامل بشن، حتی escape sequences. برای regex یا JSON عالیه!
String Templates پیشرفته:
// در raw string
val regex = """\d+""".toRegex()
// با expression
val result = "Sum: ${5 + 3}" // "Sum: 8"
// با function call
val upper = "Text: ${"hello".uppercase()}" // "Text: HELLO"
تمرینهای عملی
برای تثبیت یادگیری این درس تمرینهای زیر را حل کنید
تمرین: Strings
Easy
سوال تمرین
🎯 تمرین: String Interpolation
یک string با interpolation بنویسید.
پاسخ تمرین
KOTLIN
val name = "Ali"
val age = 25
val message = "My name is $name and I'm $age years old"
println(message)
آماده رفتن به درس بعدی هستید؟
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.