题目

const 与引用:只读遍历字符串

思路

只读遍历字符串:用下标或增强 for 逐个 System.out.print,不对原串做修改。

解题分析

const char *p 表示不能通过 p 改字符,p 本身可以指向别处。只读遍历用 const 表达意图,写入会编译报错。

完整程序

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String s = "hi";
        for (int i = 0; i < s.length(); i++) System.out.println(s.charAt(i));
    }
}

运行示例

输出:

h
i