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. :)
How do I print just the even or odd chars in an array?
Just a minor mistake in the code:
You don't need the first value from the array to initialize the loop variable i
, just the index value you want the loop to start from.
One tricky thing to keep in mind is that the indexing starts from 0, but we, humans count from 1. (I did a mistake with this in the first edit of the answer too) So the characterss with even ordinals will be printed when the start value is odd.
The start of indexing is quite a common issue one has to constantly keep in mind...
Also, you can print characters directly, you don't need the Arrays.toString() method here:
System.out.println(t[index]);
Is enough.
Odd chars: set i
to 0: this will print the 1st, 3rd ... characters
for(int i = 0; i < t.length; i = i + 2){
System.out.println(t[i]);
}
Even chars: set i
to 1: this will print the 2nd, 4th ... chars
for(int i = 1; i < t.length; i = i + 2){
System.out.println(t[i]);
}
Eliminating the array
Also, you don't even need to create a char array, you could use String.charAt(int index) for this purpose:
String even_odd = sc.next();
for(int i = 0; i < even_odd.length(); i = i + 2){
System.out.println(even_odd.charAt(i));
}
Taking it to the next level
Also, to be extra nice, you could extract this into a function, and reuse the functionality:
private static void printChars(String input, boolean even) {
int i = 0;
if(even) { //if we need the even chars, start from 1;
i=1;
}
for(; i < input.length(); i = i + 2){
System.out.println(input.charAt(i));
}
}
And then your main method would be just this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String even_odd = sc.next();
char[] t = even_odd.toCharArray();
System.out.println(Arrays.toString(t));
//calling the function for even numbers
printChars(even_odd, true);
//calling the function for odd numbers
printChars(even_odd, false);
}
Remember duplication is bad. Reuse --> good.
Split a string in java according to characters with even or odd order
I used two strings called odd and even and set both of them to be empty then i iterate throught all the letters of the string s and add the even characters to even and odd characters to odd like the following:
String S = "alfabet";
String odd="";String even="";
for(int c=0;c<S.length();c++)
{
if(c%2==0)odd+=S.charAt(c);
else even+=S.charAt(c);
}
printing character at even and odd position of a multiple strings
You are restricting yourself to an archaic version of C syntax that required all local variables to be declared at the top of a block, ahead of any executable statements.
Since your code is not using variables other than count
outside the do
/while
loop, you should move their declarations inside the loop. This will ensure that the variables have appropriate initial values at the beginning of each iteration.
Here are a few additional points to keep in mind:
- Your code will result in undefined behavior if an end-user terminates the input stream (Ctrl+Z on Windows, Ctrl+D on UNIX) without entering any characters
- Your code will drop the last character when end-user terminates input stream after entering less than ten characters
odd[0]=even[0]='\0'
is unnecessary
How to get odd and even position characters from a string?
It would probably be easier to use a regular expression and .replace
: capture two characters in separate capturing groups, add the first character to a string, and replace with the second character. Then, you'll have first half of the output you need in one string, and the second in another: just concatenate them together and return:
function encrypt(text) { let removedText = ''; const replacedText1 = text.replace(/(.)(.)?/g, (_, firstChar, secondChar) => { // in case the match was at the end of the string, // and the string has an odd number of characters: if (!secondChar) secondChar = ''; // remove the firstChar from the string, while adding it to removedText: removedText += firstChar; return secondChar; }); return replacedText1 + removedText;}console.log(encrypt('This is a test!'));
Why am I not getting the correct output in ques of printing even and odd index character seperatly?
Your int n = sc.nextInt();
consumes the integer that's input (2), but there is a still a newline.
When your loop goes through the first time, and you call String name = sc.nextLine();
, it will consume that remaining newline (and nothing else). Hence, your blank line.
To get past that, make sure to read in the new line after you read in n
Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)
Even-indexed and odd-indexed - Java
There error is being produced because array
is being using in display
which is outside of the scope you declared it in.
To fix that, you can either declare array
as an instance variable (outside of any methods), or pass the array as a parameter to display
.
Also, to get a character array from the string, use S.toCharArray()
.
import java.io.*;
import java.util.*;
public class Trying4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of words: ");
int numWords = in.nextInt();
in.nextLine(); // consume the new-line character after the number
for(int i = 0; i < numWords; i++) {
char[] word = in.nextLine().toCharArray();
display(word);
}
}
public static void display(char[] word) {
for(int i = 0; i < word.length; i += 2) {
System.out.print(word[i]);
}
System.out.print(" ");
for(int i = 1; i < word.length; j += 2) {
System.out.print(word[i]);
}
System.out.println();
}
}
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)
A program that prints even and odd characters from a string
this declaration is wrong:
char *str[41];
you're declaring 41 uninitialized strings. You want:
char str[41];
then, scanf("%40s" , str);
, no &
and limit the input size (safety)
then the loop (where your while (str[i]<41)
is wrong, it probably ends at once since letters start at 65 (ascii code for "A"). You wanted to test i
against 41 but test str[i]
against \0
instead, else you get all the garbage after nul-termination char in one of odd
or even
strings if the string is not exactly 40 bytes long)
while (str[i]) {
if (i % 2 == 0) {
odd[j++] = str[i];
} else {
even[k++] = str[i];
}
i++;
}
if you want to use a pointer (assignement requirement), just define str
as before:
char str[41];
scan the input value on it as indicated above, then point on it:
char *p = str;
And now that you defined a pointer on a buffer, if you're required to use deference instead of index access you can do:
while (*p) { // test end of string termination
if (i % 2 == 0) { // if ((p-str) % 2 == 0) { would allow to get rid of i
odd[j++] = *p;
} else {
even[k++] = *p;
}
p++;
i++;
}
(we have to increase i
for the even/odd test, or we would have to test p-str
evenness)
aaaand last classical mistake (thanks to last-minute comments), even
& odd
aren't null terminated so the risk of getting garbage at the end when printing them, you need:
even[k] = odd[j] = '\0';
(as another answer states, check the concept of even & odd, the expected result may be the other way round)
Related Topics
How to Set a Timeout on a Spring Boot Rest API
Java Spring Boot Test: How to Exclude Java Configuration Class from Test Context
Regular Expression for Uppercase Letters in a String
Java Socket Api: How to Tell If a Connection Has Been Closed
Spring Data JPA and Parameters That Can Be Null
How to Use Jackson to Deserialise an Array of Objects
Passing List from Thymeleaf to Spring Controller
How to Modify a Field in Each Element of List in Java 8 Using Stream
Reading a Resource File from Within Jar
Regular Expression (Regex). How to Ignore or Exclude Everything in Between
Find Difference Between Two Strings
Java - How to Write My Arraylist to a File, and Read (Load) That File to the Original Arraylist
Spring Junit: How to Mock Autowired Component in Autowired Component
Error Says It's Dividing by Zero While It's Not Initialised as Zero
Gradle: How to Exclude a Particular Package from a Jar
How to Convert Date Which I Got from Firebase Server as Am Getting Error Date