0

I am trying to return the index of the element containing character 'r' which has charcater 'u' as its successor. The following piece of code always returns the varialbe ruindex =0. Please suggest edits in the code.

    int ruindex=0;
    if (s1[0]=='h') {
        s2[0] = 'h';
        s2[1] = 't';
        s2[2] = 't';
        s2[3] = 'p';
        s2[4] = ':';
        s2[5] = '/';
        s2[6] = '/';

        for (int i=4; i < s1.length-1; i++) {
            if (s1[i]=='r' && s1[i+1]=='u') {
                ruindex = i;
                break;
            }
        }
    }

It is just a part of my overall code. Yes there is a reason why I want to start from i=4. What I wish to do is that whenever I encounter 'r' and 'u' together in the character array, I want to return the index of that 'r'.

4
  • 4
    First of all: format your code in a readable way Commented Sep 26, 2013 at 9:58
  • I doubt that this code will compile. Commented Sep 26, 2013 at 10:01
  • Is there a reason you're starting from i=4, you're only setting up s2 if the first value of s1 is h, there isn't this r in s2 you're looking for and what does s1 and s2 mean here, why are there 2 separate variables? Please elaborate on your requirements and provide an SSCCE. Commented Sep 26, 2013 at 10:01
  • 2
    Add declaration of s1 Commented Sep 26, 2013 at 10:03

2 Answers 2

3

How about

String s2 = new String(s1);
s2.indexOf("ru");

?

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

2 Comments

Given a string "hlolrulolru", would the above piece of code return 4?
do you have google "installed" to search for the java doc of indexOf method of String class? :)
0

Your code does affect index of first encountered "ru" to ruindex variable if arrays are initialized and populated. However you should change the loop to

for (int i = 4; i < s1.length - 1; i++) {

or you'll get an ArrayOutOfBoundsException if 'r' is the last character of the array and there are no matches before.

Anyway it seems to me that you should consider working with Strings, rather than arrays. You'll be able to use dedicated methods to achieve your goal or even use regular expressions if your goal becomes more complicate than this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.