编写程序将两个字符串连成一个新的字符串?

编写程序将两个字符串连成一个新的字符串?,第1张

Java 程序中连接两个字符最简单的是通过连接符 “+”,比如: String str = "123" + "456"

也可以使用 StringBuilder 来拼接字符串,比如: 

先创建一个 StringBuilder , StringBuilder sb = new StringBuilder()

然后使用 append 方法连接, sb.append("123").append("456")

最后通过 toString 方法获得新的字符串, String str = sb.toString()

下面提供一个代码示例,仅供参考:

public class ConcatStr {

public static void main(String[] args) {

String num1 = "123"

String num2 = "456"

String num3 = "789"

System.out.println(concatByJiaHao(num1, num2))// 123456

System.out.println(concatByStringBuilder(num2, num3))// 456789

}

public static String concatByJiaHao(String... strings){

String result = ""

for(String str : strings){

result += str

}

return result

}

public static String concatByStringBuilder(String... strings){

StringBuilder sb = new StringBuilder()

for (String str : strings){

sb.append(str)

}

return sb.toString()

}

}

void fun (char s1[],char s2[]){

int i,j

for (i=0s1[i] !=’\0’i++)/*求出的i为pA字符的总长度,包括结束标记位*/

for (j=0s2[j] !=’\0’j++)

s1[i++]=s2[j]/*将pB字符串连在pA字符串的后面*/

s1[i]='\0’/*在字符串最后加上结束标记符*/

}

扩展资料:

最常用的字符串函数

字符串输出函数puts格式:puts (字符数组名) 功能:把字符数组中的字符串输出到显示器。

2.字符串输入函数gets格式:gets (字符数组名) 功能:从标准输入设备键盘上输入一个字符串。本函数得到一个函数值,即为该字符数组的首地址。

3.字符串连接函数strcat格式:strcat (字符数组名1,字符数组名2) 功能:把字符数组2中的字符串连接到字符数组1 中字符串的后面,并删去字符串1后的串标志“”。

4.字符串拷贝函数strcpy格式:strcpy (字符数组名1,字符数组名2) 功能:把字符数组2中的字符串拷贝到字符数组1中。串结束标志“”也一同拷贝。

5.字符串比较函数strcmp格式:strcmp(字符数组名1,字符数组名2) 功能:按照ASCII码顺序比较两个数组中的字符串,并由函数返回值返回比较结果。

6.测字符串长度函数strlen格式:strlen(字符数组名) 功能:测字符串的实际长度(不含字符串结束标志‘’) 并作为函数返回值。

参考资料:

百度百科-数组

#include <stdio.h>

int main()

{

char s1[80],s2[40]

int i=0,j=0

printf("\nInput the first string:")

scanf("%s",s1)

printf("\nInput the second string:")

scanf("%s",s2)

while (s1[i] !='\0')

i++

while (s2[j] !='\0')

s1[i++]=s2[j++] /* 拼接字符到s1 */

s1[i] ='\0'

printf("\nNew string: %s",s1)

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/7756393.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-09
下一篇 2023-04-09

发表评论

登录后才能评论

评论列表(0条)

保存