How to Print the Even-Indexed and Odd-Indexed Characters of Strings

How to print even and odd position characters of an array of strings in Java?

int T = scan.nextInt();

This reads quantity of test cases, which we're going to process.

String string[] = new String[T];
for(int i = 0; i<T; i++){
string[i] = scan.next();

}
Next we're creating an array named "string" (BTW, this a bad name for variables/objects) which has size T and in the for loop reading test cases from the input T times and saving them in the array.

for(int temp = 0; temp<T; temp++){

Now, for each of test cases we do the following...

for(int j = 0; j<string[temp].length(); j = j+2)
{
System.out.print(string[temp].charAt(j));
}

We create a local variable j, which is visible only in this for loop. j holds index of the string (=string[temp]), which we're processing. So, we're printing a character on position j (by using standard method "charAt" of String class, which returns character of given index of the string) and then increasing it by 2. So, this code will print every even character. For string "example", it will print "eape" (j=0, j=2, j=4, j=6).

System.out.print(" ");

Separating sequences with a space.

for(int j = 1; j<string[temp].length(); j = j+2){
System.out.print(string[temp].charAt(j));
}

System.out.println();

We're doing the same (creating index j, running though all characters of the string), but starting from "1", so it will print all odd characters of the string. For string "example", it will give you "xml" (j=1, j=3, j=5). and After this, it will end the string. I hope, it will help you to understand. :)

Print characters at even and odd indices from a String

Here is a tail-recursive solution returning even and odd chars (List[Char], List[Char]) in one go

def f(in: String): (List[Char], List[Char]) = {
@tailrec def run(s: String, idx: Int, accEven: List[Char], accOdd: List[Char]): (List[Char], List[Char]) = {
if (idx < 0) (accEven, accOdd)
else if (idx % 2 == 0) run(s, idx - 1, s.charAt(idx) :: accEven, accOdd)
else run(s, idx - 1, accEven, s.charAt(idx) :: accOdd)
}
run(in, in.length - 1, Nil, Nil)
}

which could be printed like so

val (even, odd) = f("abcdefg")
println(even.mkString)

Failing the test cases in printing the even-indexed and odd-indexed characters of strings

This would be the correct main, if I understood the task correctly:

int main() 
{
int count = 0;
cin >> count;

for(int i = 0; i < count; i++){
string s1;
cin>>s1;
sum(s1);
}

return 0;
}


Related Topics



Leave a reply



Submit