kotlin

In this tutorial, we’ll be discussing at length an important data type of Kotlin, namely Kotlin String. It’s recommended to read Introduction to Kotlin tutorial before proceeding ahead.

在本教程中,我们将详细讨论Kotlin的一种重要数据类型,即Kotlin String。 建议先阅读Kotlin入门教程,然后再继续。

Kotlin弦 (Kotlin String)

String is an array of characters. Kotlin Strings are more or less similar to the Java Strings, but with some new add-ons. Following is the syntax to define a string.

字符串是字符数组。 Kotlin字符串或多或少类似于Java字符串,但带有一些新的附加组件。 以下是定义字符串的语法。

var str: String  = "Hello"//or
var str = "Hello"var newString: String = 'A' //ERROR
var newString: String = 2 //ERROR

String in Kotlin is implemented using the String class. Like Java String, Kotlin Strings are immutable.

Kotlin中的String是使用String类实现的。 像Java String一样,Kotlin Strings是不可变的。

var str  = "Hello"
str += "Kotlin Strings"

The above declaration changes the reference of the variable str in the second line to the newly created string(“Hello Kotlin Strings”) in the String Pool.

上面的声明将第二行中变量str的引用更改为String Pool中新创建的字符串(“ Hello Kotlin Strings”)。

Creating an empty String

创建一个空字符串

var s = String() //creates an empty string.

Unlike Java, Kotlin doesn’t require a new keyword to instantiate an object of a class.

与Java不同,Kotlin不需要new关键字来实例化类的对象。

Kotlin弦的重要属性和功能 (Important Properties and Functions of Kotlin String)

  • length : This is a property that can be accessed using the dot operator on the String. Returns the number of characters present in a string.

    val str = "Hello Kotlin Strings"
    println(str.length) //prints 20

    length :这是一个属性,可以使用String上的点运算符进行访问。 返回字符串中存在的字符数。

  • get(index) : Returns the character specified at the particular index.get(index) :返回在特定索引处指定的字符。
  • subSequence(startIndex, endIndex) : Returns the substring between the startIndex and the endIndex but excluding the endIndex character.
    val str = "Hello Kotlin Strings"
    println(str.subSequence(0,5)) //prints Hello

    subSequence(startIndex, endIndex) :返回介于startIndexendIndex之间的子字符串,但不包括endIndex字符。

  • a.compareTo(b) : If a is equal to b, it returns 0, if a<b it returns positive number. compareTo accepts another argument too, namely ignoreCase.
    var str  = "Hello Kotlin Strings"
    var s = String()
    s = "Hello KOTLIN Strings"
    println(s.compareTo(str)) //prints -32
    println(s.compareTo(str,true)) //prints 0

    a.compareTo(b) :如果a等于b,则返回0,如果a <b,则返回正数。 compareTo也接受另一个参数,即ignoreCase

访问字符串中的字符 (Accessing Characters in a String)

To access individual characters of a String, Kotlin supports the index access operator(Unlike Java) as shown below.
Using Index Operator

要访问String的各个字符,Kotlin支持索引访问运算符(不同于Java),如下所示。
使用索引运算符

var str = "Hello, Kotlin"
print(str[0]) //prints H

Using the get method

使用get方法

val str = "Hello Kotlin Strings"
println(str.get(4)) //prints o

Iterating through a String
We can loop through a string to access each character using a for-in loop as shown below.

遍历字符串
我们可以使用for-in循环遍历字符串以访问每个字符,如下所示。

for(element in str){println(element)}

Kotlin字符串中的转义字符 (Escape characters in Kotlin Strings)

Following are the escape characters that when used with a backslash behave differently.

以下是与反斜杠一起使用时的转义字符,其行为有所不同。

  • \n newline.\n换行符。
  • \r carriage return.\r回车。
  • \t tab.\t标签。
  • \b backspace\b退格键
  • \" double quote\"双引号
  • \' single quote\'单引号
  • \\ backslash\\反斜杠
  • \$ dollar – Dollar symbol is used in String templates that we’ll be seeing next\$ dollar –在字符串模板中使用美元符号,我们接下来将看到
  • 字符串模板 (String Templates)

    Instead of concatenating an expression in a string, Strings can contain expressions/statements following a dollar symbol as shown below.

    代替在字符串中连接表达式,字符串可以包含在美元符号后面的表达式/语句,如下所示。

    var len = str.length
    var newStr = "Length of str is ${str.length}"
    //or
    var newStr = "Length of str is $len"println(Length of str is ${str.length})

    Using string templates, we can insert variables and expressions in a string. String Templates are commonly used in print statements.
    To use the $ symbol in a string we need to escape the character.

    使用字符串模板,我们可以在字符串中插入变量和表达式。 字符串模板通常在print语句中使用。
    要在字符串中使用$符号,我们需要对字符进行转义。

    var escapedDollar = "Amount is \$5.50"
    print(escapedDollar) //prints Amount is $5.50

    原始字符串–多行字符串 (Raw Strings – Multiline String)

    Raw strings are strings placed inside triple quotes. We don’t have to escape characters in triple-quoted strings. These strings can be used in multi lines without the need to concatenate each line.

    原始字符串是放在三重引号内的字符串。 我们不必用三引号引起来的字符转义。 这些字符串可以在多行中使用,而无需连接每行。

    var rawString = """Hi How you're DoingI'm doing fine.I owe you $5.50"""
    print(rawString)//Prints the following in the console
    Hi How you're DoingI'm doing fine.I owe you $5.50

    Note: Since escape characters are not parsed, adding a \n or \t won’t have any effect.

    注意 :由于未解析转义字符,因此添加\ n或\ t不会有任何效果。

    var rawString = """Hi How you're DoingI'm doing fine\n.I owe you $5.50"""print(rawString)//prints the following
    Hi How you're DoingI'm doing fine\n.I owe you $5.50

    Raw strings are handy when you need to specify a file/directory path in a string.
    We can indent raw strings or remove the whitespacing in multi-lines using the function trimMargin().

    当您需要在字符串中指定文件/目录路径时,使用原始字符串非常方便。
    我们可以使用函数trimMargin()缩进原始字符串或多行删除空格。

    var rawString = """Hi How you're Doing|I'm doing fine.|I owe you $5.50""".trimMargin("|")print(rawString)
    //Prints the following to the console.Hi How you're Doing
    I'm doing fine.
    I owe you $5.50

    Note: We can’t pass a blank string as the trim margin. The trimMargin() function trims the string till the marginPrefix specified.

    注意:我们不能传递空白字符串作为修剪边距。 trimMargin()函数将字符串修剪到指定的marginPrefix为止。

    String templates and Raw Strings can be combined together as shown below.

    字符串模板和原始字符串可以组合在一起,如下所示。

    var str = "Kotlin"
    var rawString = """Hi How you're Doing $str|I'm doing fine.|I owe you $5.50""".trimMargin("|")
    print(rawString)//The following gets printed on the consoleHi How you're Doing Kotlin
    I'm doing fine.
    I owe you $5.50

    覆盖字符串方法 (Overriding String method)

    In Java, we commonly override toString() method of a class to display the contents of the class’s instance object. Similar stuff happens in Kotlin too as shown below.

    在Java中,我们通常重写类的toString()方法以显示该类的实例对象的内容。 如下所示,在Kotlin中也发生了类似的事情。

    class Student(var name: String, var age: Int)
    {//Define properties and functions here.
    }//The following code is written inside the main function of the Kotlin class.
    var student = Student("Anupam", 23)
    print(student) //prints com.journaldev.Strings.Student@34a245ab

    Printing the above object doesn’t give any idea about the variables initialised.
    Here’s where we override the toString() method as shown below.

    打印上面的对象不会对初始化的变量有任何想法。
    此处是我们重写toString()方法的地方,如下所示。

    class Student(var name: String, var age: Int)
    {override fun toString(): String {return "Student name is $name and age is $age"}
    }//The following code is written inside the main function of the Kotlin class.
    var student = Student("Anupam", 23)
    print(student) //prints Student name is Anupam and age is 23

    Note: Unlike Java, Kotlin doesn’t require a new keyword to initialize the constructor of a class.

    注意 :与Java不同,Kotlin不需要new关键字即可初始化类的构造函数。

    字符串相等 (String Equality)

    There are two types of equality checkers.

    有两种类型的相等性检查器。

    • Referential Equality: Checks if the pointers for two objects are the same. === operator is used.引用相等 :检查两个对象的指针是否相同。 ===运算符。
    • Structural Equality : Checks if the contents of both the objects are equal. == is used.结构相等 :检查两个对象的内容是否相等。 ==被使用。

    Following code snippet demonstrates the above checkers.

    以下代码段演示了上述检查器。

    var a = "Hello"
    var b = "Hello again"
    var c = "Hello"
    var d1 = "Hel"
    var d2 ="lo"
    var d = d1 + d2println(a===c) // true since a and c objects point to the same String in the StringPool
    println(a==c) //true since contents are equal
    println(a===b) //false
    println(a==b) //false
    println(a===d) //false since d is made up of two different Strings. Hence a and d point to different                            set of strings
    println(a==d) //true since the contents are equal

    Note: The negation of === and == are !=== and !== respectively.

    注意:===和==的取反分别是!===和!==。

    This brings an end to kotlin string tutorial.

    这样就结束了kotlin字符串教程。

    翻译自: https://www.journaldev.com/17318/kotlin-string

    kotlin

kotlin_Kotlin弦相关推荐

  1. P3196 [HNOI2008]神奇的国度(弦图的最小染色问题)

    整理的算法模板合集: ACM模板 题目传送门 K国是一个热衷三角形的国度,连人的交往也只喜欢三角原则.他们认为三角关系:即AB相互认识,BC相互认识,CA相互认识,是简洁高效的.为了巩固三角关系,K国 ...

  2. 弦截法c语言程序,高数介质定理——弦截法求根代码实践(C语言)

    在高等数学中,我们一开始接触概念时就接受了ε-δ(epsilon-delta)语言的洗礼,但即使到课程的结束,许多人依然会对各种抽象的数学符号.定理证明感到无所适从,我也不例外,尽管在写这篇博客以前已 ...

  3. 无向图的完美消除序列 判断弦图 ZOJ 1015 Fish net

       ZOJ1015 题意简述:给定一个无向图,判断是否存在一个长度大于3的环路,且其上没有弦(连接环上不同两点的边且不在环上). 命题等价于该图是否存在完美消除序列. 所谓完美消除序列:在 vi,v ...

  4. python 求两条曲线的交点_这几种问法都是考察张角问题,高考数学圆锥曲线的焦点弦张角定理...

    在高考数学的圆锥曲线中,有很多神奇的问法,比如 (1)在x轴上是否存在点Q,使得∠PQM+∠PQN=180° (2)在x轴上是否存在一点B使得∠ABM=∠ABN: (3)在x轴上是否存在定点Q,使得直 ...

  5. boost::sort模块实现弦平面稳定测试

    boost::sort模块实现弦平面稳定测试 实现功能 C++实现代码 实现功能 boost::sort模块实现弦平面稳定测试 C++实现代码 #include <algorithm> # ...

  6. d3.js中点可以用图片吗_结论第16课——抛物线的中点弦斜率

    秒杀结论: 中点弦斜率="左右 除 ,上下 除 " 注意要加上抛物线开口方向所确定的符号: 开口向右和向上的,符号为正 开口向左和向下的,符号为负 原理: 例.点 是抛物线 上两点 ...

  7. 牛客 - 弦(卡特兰数)

    题目链接:点击查看 题目大意:给定一个圆,圆上有2N个互不重叠的点.每次操作随机选择两个先前未选择过的点连一条弦,共连成N条弦,求所有弦不交的概率. 题目分析:圆内连弦是卡特兰数的经典应用,如果将最后 ...

  8. 『数学』你确定你学会了勾股弦定理!真的吗?看完这个篇文章再回答我!

    勾股定理: 勾股定理,又称"毕达哥拉斯定理",是初等几何中的一个基本定理.这个定理有十分悠久的历史,两千多年来,人们对勾股定理的证明颇感兴趣,因为这个定理太贴近人们的生活实际,以至 ...

  9. 年月跨度_建筑结构丨国内跨度最大的张弦桁架工程——合肥滨湖国际会展中心二期首榀桁架滑移成功...

    来源:中建科工 华中大区. 2020年12月8日 全国公建领域最大跨度的张弦桁架钢结构工程 合肥滨湖国际会展中心二期 首榀桁架滑移顺利完成 合肥滨湖国际会展中心二期项目位于合肥市滨湖新区锦绣大道与广西 ...

最新文章

  1. C#中DictionaryTKey,TValue排序方式
  2. python实例 73,74
  3. SU(Seismic Unix)与CUDA的混合编程
  4. 初识 Node.js
  5. python cls方法
  6. 459.重复的子字符串
  7. 一位ML工程师构建深度神经网络的实用技巧
  8. 面向对象系列(一)-关键字
  9. 2022年最新广播电视广告报价(共23份)
  10. CheckBox和ListView的结合使用
  11. 推荐一款好用的CopyTranslator 翻译工具
  12. vbs字符串正则_VBS正则表达式语法
  13. 如何构建一个在线绘图工具:Feakin 是如何设计与构建的?
  14. linux的简体中文
  15. VSCode中ESLint插件修复+配置教程
  16. 哪个邮箱群发效果好?邮件可以群发吗?群发邮件技巧教程来了
  17. Django简洁留言板系统
  18. 【WaterRemind】用Arduino与SSD1306做一款提醒喝水的杯垫(何同学同款)
  19. GIS开发/WebGIS开发零基础入门:地图域当前信息(附代码)
  20. java 文件名查找_java 查找目录下指定文件名的文件

热门文章

  1. mysql 查询表注释
  2. [转载] 【原创】Python 3 查看字符编码方法
  3. [转载] Python中协程的详细用法和例子
  4. verilog系统任务之$random
  5. 牛客Wannafly挑战赛10 A.小H和迷宫
  6. 关于前端样式定位的一些自己的看法
  7. EasyUI文档学习心得
  8. ubuntu PIL出错 重新安装
  9. Linux安装卸载Mysql数据库
  10. 诊断Oracle 服从成绩