当前位置:网站首页>字符串的遍历及拼接
字符串的遍历及拼接
2022-07-24 18:34:00 【The code family】
字符串的遍历:
需求:键盘录入一个字符串,使用程序实现在控制台遍历该字符串
思路:
①键盘录入一个字符串,用Scanner实现
②遍历字符串,首先要能够获取到字符串中的每一个字符
●public char charAt(int index):返回指定索引处的char值,字符串的索引也是从0开始的
③遍历字符串,其次要能够获取到字符串的长度
●public int length():返回此字符串的长度
●数组的长度:数组名.length
●字符串的长度: 字符串对象.length()
④遍历字符串的通用格式
for(int i=0; i<s.length(); i++) {
s. charAt(i); // 就是指定索引处的字符值
}
import java.util.Scanner;
public class _02_String {
public static void main(String[] args) {
//键盘录入一个字符串,用Scanner实现
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
//遍历字符串,首先要能够获取到字符串中的每一个字符
for (int i = 0; i < line.length(); i++) {
System.out.println(line.charAt(i));
}
}
}
字符串的拼接
需求:定义一个方法,把int数组中的数据按照指定的格式拼接成一个字符串返回, 调用该方法,并在控制台输出结果。例如,数组为int[] arr= {1,2,3};,执行方法后的输出结果为: [1,2, 3]
思路:
①定义一个int类型的数组,用静态初始化完成数组元素的初始化
②定义一个方法,用于把int数组中的数据按照指定格式拼接成一个字符串返回。返回值类型String,参数列表int[] arr
③在方法中遍历数组,按照要求进行拼接
④调用方法,用一个变量接收结果
⑤输出结果
public class _04_String {
public static void main(String[] args) {
//定义一个int类型的数组,用静态初始化完成数组元素的初始化
int[] arr = {
1, 2, 3};
//调用方法,用一个变量接收结果
String s = arrayToString(arr);
//输出结果
System.out.println("s:" + s);
}
//定义一个方法,用于把int数组中的数据按照指定格式拼接成一个字符串返回
/* 两个明确: 返回值类型: String 参数: int[] arr */
public static String arrayToString(int[] arr) {
String s = "";
//在方法中遍历数组,按照要求进行拼接
s = s + "[";
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
s = s + arr[i];
} else {
s = s + arr[i] + ',';
}
}
s = s + "]";
return s;
}
}
边栏推荐
- Ionic4 Learning Notes 6 -- using native ionic4 components in custom components
- 第五届数字中国建设峰会在福建福州开幕
- mysql 配置文件
- 全国职业院校技能大赛网络安全竞赛——Apache安全配置详解
- MySQL configuration file
- Common methods of array (2)
- 树链剖分板子
- Typora is still the most beautiful and beautiful document editing artifact of yyds in my heart. I believe you will never abandon it
- 8. = = and = = =?
- 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
猜你喜欢
随机推荐
Cryptography knowledge - Introduction to encryption -1
Rookie colleagues cost me 2K. Did you recite the secret of salary increase? (collect it quickly!)
Eternal Blue ms17-010exp reappears
QT—动画框架
Some buckles
Get familiar with pytoch and pytoch environment configuration
理解corners_align,两种看待像素的视角
The collapse of margin
Getaverse,走向Web3的远方桥梁
Pytoch's journey 1: linear model
Ionic4 learning notes 11 - popular goods display of an East Project
Wechat applet
Problems needing attention in writing pages
Custom web framework
Pycharm configuring opencv Library
Ionic4 learning notes 9 -- an east project 01
Valentine's Day gift ----- use her photos and our chat records to generate word clouds~
Ionic4 learning notes 10 rotation map of an East Project
EasyUI framework dialog repeated loading problem
Read zepto source code touch module









