Pick out Java strings

Asked 2 years ago, Updated 2 years ago, 20 views

I want to know that the string s2 contains any string, and I want to pick a from it.

First of all,

public class Ex02 {

    public static void main(String[] args) {
        String s2 = "asdjkfhakgba";

        //Select by array
        char[] arr = s2.toCharArray();

//      //      for(int i = 0; i < arr.length; i++) {
//          //          System.out.print(arr[i]);
//      }

        System.out.println ("Answer: " + arr[0] + arr[7] + arr[11]);
    }
}

Like this, aaa came out, but I thought it was a little inefficient. Is it possible to just read the string instead of reading it in an array? Or if there is any other way, I wonder.

java

2022-09-20 21:57

1 Answers

I thought it was javascript, so it's javas. --;

By the way, I looked up Java and found the same string method.

Use indexOf() to count specific characters in a string

First of all, refer to the javascript code in the link above and implement it as javas. I haven't used java that much. There's a way like this Please refer to it)

class CodeRunner{
    public static void main(String[] args){
        String s2 = "asdjkfhakgba", search_str="a";
        int count = -1, pos = -1;            
        do {
            count++;
            pos = s2.indexOf(search_str, pos + 1); 
        } } while(pos != -1);
        System.out.println ("Answer: " + (count>0) ? search_str.repeat(count) : "None"));
    }
}


2022-09-20 21:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.