有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中遍历字符串而不使用任何内置方法?

对不起,问题不清楚。我想做的是所有可以在字符数组上完成的操作(比如检索字符数组中的每个字符,查找单词之间的空格,查找数组的结尾等等)。在C和C++中,我可以使用循环语句遍历整个数组(按字符计算)。但我无法在java中做到这一点。为此,我不得不使用toCharArray()方法或charAt()方法。除此之外还有其他逻辑吗?。更具体地说,是否有任何方法可以将字符串转换为字符数组,而不使用任何(any!!)内置方法(即API)


共 (3) 个答案

  1. # 1 楼答案

    您可以使用getBytes()toCharArray()获取字符串的原始字符:

    String string = "lorem ipsum";
    byte[] bytes = string.getBytes();
    
    for(int i = 0; i < bytes.length; i++){
        if(bytes[i] == 0x20){ // ASCII code of space
            System.out.println("Found space at index "+i);
        }
    }
    
  2. # 2 楼答案

    你的问题很模糊。我假设您希望在不使用charAt()方法的情况下查找字符串的最后一个字符

        String example = "I like Java";
        int size = example.length(); //gives the length of the string
    
        //cuts the string for the last char
        String lastChar = example.subString((size-2), (size-1)); 
    
  3. # 3 楼答案

    如果唯一的限制是不使用charAt(),则使用toCharArray()

    String hello = "Hello dummy, why can't I use charAt";
    
    char[] letters = hello.toCharArray();
    
    // traverse array
    

    编辑:查找空间

    if (hello[i] == ' ')
    

    编辑:遍历字符串

    character array(such as retrieving each character in character array,finding spaces between words,finding end of array,etc
    
    // traverses through every character in String
    for (int i = o; i <hello.length(); i++){
        char c = hello.charAt(i);  
        System.out.println(c); // prints out every char of string
    
        if (Charcter.isWhiteSpace(hello.charAt(i)){ // checks if char is white space
            // do something
        }
    
        if (c == ' ') {  // checks if char is whitespace
            // do something
        }
    }
    
    // last letter
    char c = hello.charAt(hello.length() - 1);
    

    您应该真正查看Stringjava文档,以查看其所有可用的方法。甚至可以查看Character类javadocs