everyNth

Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, … and so on. N is 1 or more.

everyNth(“Miracle”, 2) ? “Mrce”
everyNth(“abcdefg”, 2) ? “aceg”
everyNth(“abcdefg”, 3) ? “adg”

public String everyNth(String str, int n) {
//char c[]=str.toCharArray();
String str1="";
for(int i=0;i<str.length();i++)
{ if(i%n ==0)
str1=str1+str.substring(i,i+1);
}
return str1;
}
Advertisements

One thought on “everyNth

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s