wayoo
wayoo

Reputation: 125

Editing strings with java methods

I am currently studying methods in java, I have used methods to work with arrays but I am having trouble using them with strings.

One of the problems I have is given a string, and a number. I have to print charAt(0) of the string, then every int of the string after.

For example, "Programming" and the number 3 would yield "Pgmn"

If I was to do this without methods I could. But I am not sure how to construct it with a method.

Upvotes: 0

Views: 80

Answers (2)

nbro
nbro

Reputation: 15837

You can iterate using different jumps from 1. For example:

public void printCharsWithJumps(String s, int jump){
    for(int i=0; i<s.length(); i += jump){ // adding jump to i each time
        System.out.print(s.charAt(i));
    }       
}

Note that I am adding 3 to the loop variable i each time, instead of the usual i++, which simply increments i by 1.

Upvotes: 2

Srini
Srini

Reputation: 1636

In the solution below, str is a parameter to the method which will contain the String in question.

x is an int which represents the 'number' in question i.e. we'll print every xth character starting from the second character.

The call to this method will be made like this:

printDesiredCharacters("Programming", 3);



 void printDesiredCharacters(String str, int x)
{
    char[] arr = str.toCharArray();
    System.out.print(arr[0]); //Print first character
    for(int index = x; index < arr.length; index += x)
    {
        System.out.print(arr[index]);//Print every character that is x spaces from the first.
    }
}

Output: Pgmn

Upvotes: 2

Related Questions