题目
练习:可变形参的方法n个字符串进行拼接,每一个字符串之间使用某字符进行分割,如果没有传入字符串,那么返回空字符串""
代码
/*** ClassName: StringConCatTest* Description:* 练习:可变形参的方法** n个字符串进行拼接,每一个字符串之间使用某字符进行分割,如果没有传入字符串,那么返回空字符串""** @Author 尚硅谷-宋红康* @Create 16:56* @Version 1.0*/ public class StringConCatTest {public static void main(String[] args) {StringConCatTest test = new StringConCatTest();String info = test.concat("-","hello","world");System.out.println(info);//hello-worldSystem.out.println(test.concat("/", "hello"));System.out.println(test.concat("-"));}//n个字符串进行拼接,每一个字符串之间使用某字符进行分割,如果没有传入字符串,那么返回空字符串""public String concat(String operator,String ... strs){String result = "";for (int i = 0;i < strs.length;i++){if(i == 0){result += strs[i];}else{result += (operator + strs[i]);}}return result;} }
代码解释
这段代码是一个 Java 程序,主要用于演示可变形参方法的使用。以下是对代码的详细解释:
1. `package chapter06_oop1_teacher.src.com.atguigu05.method_more._02args.exer;`:该行代码声明了这个 Java 类所在的包路径。
2. 类 `StringConCatTest` 被声明为公共的(`public`),这意味着其他包中的类可以访问它。
3. 在 `StringConCatTest` 类中有一个名为 `main` 的公共静态方法,它是 Java 程序的入口点。
4. 在 `main` 方法中创建了 `StringConCatTest` 类的一个实例对象 `test`。
5. `test.concat("-", "hello", "world")` 调用了类中的 `concat` 方法,用连字符 "-" 将字符串 "hello" 和 "world" 拼接起来。拼接后的结果被存储在变量 `info` 中,并打印出来。
6. `test.concat("/", "hello")` 调用了 `concat` 方法,用斜杠 "/" 将字符串 "hello" 拼接起来,结果被直接打印出来。
7. `test.concat("-")` 调用了 `concat` 方法,但没有传入其他字符串,因此返回空字符串 ""。
8. `concat` 方法是一个公共的方法,用于将传入的多个字符串按照指定的分隔符连接起来。
9. 方法签名为 `public String concat(String operator, String... strs)`,其中 `String operator` 是用于分隔字符串的操作符,`String... strs` 是可变参数,允许传入任意数量的字符串。
10. 在方法体中,首先创建一个空字符串 `result` 用于存储拼接后的结果。
11. 使用 `for` 循环遍历传入的字符串数组 `strs`。
12. 如果是第一个字符串,则直接将其加入到 `result` 中;否则,在当前字符串前面加上 `operator` 后再加入 `result` 中。
13. 最后将拼接后的 `result` 返回。
这段代码演示了如何使用可变形参方法来拼接多个字符串,并且可以指定分隔符。