1

I have a basic String variable that contains the letter x a total of three times. I have attempted to find x within the String using charAt, and then print the char and the next two characters next to it.

I have hit a snag within my code and would appreciate any help.

Here is my code.

public class StringX{
    public static void main(String[] args){
        String ss = "xarxatxm";
        char first = ss.charAt(0);
        char last == ss.charAt(3);

        if(first == "x"){ 
            String findx = ss.substring(0, 2);
        }
        if(last == "x"){
            String findX = ss.substring(3, 5);
        }

        System.out.print(findx + findX);
    }
}

Also, is there a way to implement the for loop to cycle through the String looking for x also?

I just need some advice to see where my code is going wrong.

1
  • 1
    "x" is a string and 'x' is a char Commented Feb 10, 2013 at 13:41

1 Answer 1

2

You cannot find characters using charAt - it's for getting a character once you know where it is.

Is there a way to implement the for loop to cycle through the String looking for x also?

You need to use indexOf for finding positions of characters. Pass the initial position which is the position of the last x that you found so far to get the subsequent position.

For example, the code below

String s = "xarxatxm";
int pos = -1;
while (true) {
    pos = s.indexOf('x', pos+1);
    if (pos < 0) break;
    System.out.println(pos);
}

prints 0 3 6 for the three positions of 'x' in the string.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one! I will take this code and manipulate to produce what is required. I will let you know how I get on and thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.