20.md 2.1 KB
Newer Older
W
wizardforcel 已提交
1
# Java `String concat()`方法示例
W
wizardforcel 已提交
2 3 4

> 原文: [https://beginnersbook.com/2013/12/java-string-concat-method-example/](https://beginnersbook.com/2013/12/java-string-concat-method-example/)

W
wizardforcel 已提交
5
Java 字符串`concat()`方法连接多个字符串。此方法将指定的字符串附加到给定字符串的末尾,并返回组合的字符串。我们可以使用`concat()`方法连接多个字符串。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
## `concat()`方法签名
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
```java
W
wizardforcel 已提交
10 11 12
public String concat(String str)
```

W
wizardforcel 已提交
13
此方法将字符串 str 连接到当前字符串的末尾。例如 - `s1.concat("Hello");`会在`String s1`的末尾连接字符串`"Hello"`。可以在这样的单个语句中多次调用此方法
W
wizardforcel 已提交
14

W
wizardforcel 已提交
15
```java
W
wizardforcel 已提交
16 17 18 19
String s1="Beginners";
s1= s1.concat("Book").concat(".").concat("com");
```

W
wizardforcel 已提交
20
执行上述声明后,`s1`的值将为`BeginnersBook.com`
W
wizardforcel 已提交
21

W
wizardforcel 已提交
22
## Java `String concat`方法示例
W
wizardforcel 已提交
23

W
wizardforcel 已提交
24
在这个例子中,我们将看到使用`concat()`方法进行`String`连接的两种方法。
W
wizardforcel 已提交
25

W
wizardforcel 已提交
26
```java
W
wizardforcel 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
public class ConcatenationExample {
   public static void main(String args[]) {
       //One way of doing concatenation
       String str1 = "Welcome";
       str1 = str1.concat(" to ");
       str1 = str1.concat(" String handling ");
       System.out.println(str1);

       //Other way of doing concatenation in one line
       String str2 = "This";
       str2 = str2.concat(" is").concat(" just a").concat(" String");
       System.out.println(str2);
   }
}
```

**输出:**

W
wizardforcel 已提交
45
```java
W
wizardforcel 已提交
46 47 48 49
Welcome to  String handling 
This is just a String
```

W
wizardforcel 已提交
50
## Java `String concat`方法的另一个例子
W
wizardforcel 已提交
51

W
wizardforcel 已提交
52
正如我们在上面看到的那样,`concat()`方法将[字符串](https://beginnersbook.com/2013/12/java-strings/)附加到当前字符串的末尾。但是我们可以做一个解决方法,在给定字符串的开头附加**指定的字符串。**
W
wizardforcel 已提交
53

W
wizardforcel 已提交
54
```java
W
wizardforcel 已提交
55 56 57 58 59 60 61 62 63 64
public class JavaExample {
   public static void main(String args[]) {
	String mystring = ".com";
	String mystr = "BeginnersBook".concat(mystring);
	System.out.println(mystr);
   }
}
```

**输出:**
W
wizardforcel 已提交
65

W
wizardforcel 已提交
66
![Java String concat method example](img/9bcd58d8ef15b20d4ea49746d1d600d4.jpg)