[BAEL-19882] - Move articles out of core-kotlin part1

This commit is contained in:
catalin-burcea
2019-12-10 14:57:11 +02:00
parent 3517462948
commit a141ac01fd
42 changed files with 210 additions and 124 deletions

View File

@@ -0,0 +1,9 @@
## Core Kotlin Strings
This module contains articles about core Kotlin strings.
### Relevant articles:
- [Generate a Random Alphanumeric String in Kotlin](https://www.baeldung.com/kotlin-random-alphanumeric-string)
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
- [Kotlin String Templates](https://www.baeldung.com/kotlin-string-template)

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-kotlin-strings</artifactId>
<name>core-kotlin-strings</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-kotlin-modules</groupId>
<artifactId>core-kotlin-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,115 @@
package com.baeldung.stringtemplates
/**
* Example of a useful function defined in Kotlin String class
*/
fun padExample(): String {
return "Hello".padEnd(10, '!')
}
/**
* Example of a simple string template usage
*/
fun simpleTemplate(n: Int): String {
val message = "n = $n"
return message
}
/**
* Example of a string template with a simple expression
*/
fun templateWithExpression(n: Int): String {
val message = "n + 1 = ${n + 1}"
return message
}
/**
* Example of a string template with expression containing some logic
*/
fun templateWithLogic(n: Int): String {
val message = "$n is ${if (n > 0) "positive" else "not positive"}"
return message
}
/**
* Example of nested string templates
*/
fun nestedTemplates(n: Int): String {
val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}"
return message
}
/**
* Example of joining array's element into a string with a default separator
*/
fun templateJoinArray(): String {
val numbers = listOf(1, 1, 2, 3, 5, 8)
val message = "first Fibonacci numbers: ${numbers.joinToString()}"
return message
}
/**
* Example of escaping the dollar sign
*/
fun notAStringTemplate(): String {
val message = "n = \$n"
return message
}
/**
* Example of a simple triple quoted string
*/
fun showFilePath(): String {
val path = """C:\Repository\read.me"""
return path
}
/**
* Example of a multiline string
*/
fun showMultiline(): String {
val receipt = """Item 1: $1.00
Item 2: $0.50"""
return receipt
}
/**
* Example of a multiline string with indentation
*/
fun showMultilineIndent(): String {
val receipt = """Item 1: $1.00
>Item 2: $0.50""".trimMargin(">")
return receipt
}
/**
* Example of a triple quoted string with a not-working escape sequence
*/
fun showTripleQuotedWrongEscape(): String {
val receipt = """Item 1: $1.00\nItem 2: $0.50"""
return receipt
}
/**
* Example of a triple quoted string with a correctly working escape sequence
*/
fun showTripleQuotedCorrectEscape(): String {
val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50"""
return receipt
}
fun main(args: Array<String>) {
println(padExample())
println(simpleTemplate(10))
println(templateWithExpression(5))
println(templateWithLogic(7))
println(nestedTemplates(-5))
println(templateJoinArray())
println(notAStringTemplate())
println(showFilePath())
println(showMultiline())
println(showMultilineIndent())
println(showTripleQuotedWrongEscape())
println(showTripleQuotedCorrectEscape())
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.randomstring
import org.apache.commons.lang3.RandomStringUtils
import org.junit.Before
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.security.SecureRandom
import java.util.concurrent.ThreadLocalRandom
import kotlin.experimental.and
import kotlin.streams.asSequence
import kotlin.test.assertEquals
const val STRING_LENGTH = 10
const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+"
class RandomStringUnitTest {
private val charPool : List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
@Test
fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() {
var randomString = ThreadLocalRandom.current()
.ints(STRING_LENGTH.toLong(), 0, charPool.size)
.asSequence()
.map(charPool::get)
.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingKotlin_thenReturnAlphanumericString() {
var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString() {
var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH)
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() {
val random = SecureRandom()
val bytes = ByteArray(STRING_LENGTH)
random.nextBytes(bytes)
var randomString = (0..bytes.size - 1).map { i ->
charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt())
}.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.stringcomparison
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class StringComparisonUnitTest {
@Test
fun `compare using equals operator`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first == second }
assertFalse { first == firstCapitalized }
}
@Test
fun `compare using referential equals operator`() {
val first = "kotlin"
val second = "kotlin"
val copyOfFirst = buildString { "kotlin" }
assertTrue { first === second }
assertFalse { first === copyOfFirst }
}
@Test
fun `compare using equals method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.equals(second) }
assertFalse { first.equals(firstCapitalized) }
assertTrue { first.equals(firstCapitalized, true) }
}
@Test
fun `compare using compare method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.compareTo(second) == 0 }
assertTrue { first.compareTo(firstCapitalized) == 32 }
assertTrue { firstCapitalized.compareTo(first) == -32 }
assertTrue { first.compareTo(firstCapitalized, true) == 0 }
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.stringconcatenation
import org.junit.Test
import kotlin.test.assertEquals
class StringConcatenationTest {
@Test
fun givenTwoStrings_concatenateWithTemplates_thenEquals() {
val a = "Hello"
val b = "Baeldung"
val c = "$a $b"
assertEquals("Hello Baeldung", c)
}
@Test
fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() {
val a = "Hello"
val b = "Baeldung"
val c = a + " " + b
assertEquals("Hello Baeldung", c)
}
@Test
fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() {
val a = "Hello"
val b = "Baeldung"
val builder = StringBuilder()
builder.append(a).append(" ").append(b)
val c = builder.toString()
assertEquals("Hello Baeldung", c)
}
@Test
fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() {
val a = "Hello"
val b = "Baeldung"
val c = a.plus(" ").plus(b)
assertEquals("Hello Baeldung", c)
}
}