如何在Java中打印字符串数组的偶数和奇数位置字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44135740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:22:38  来源:igfitidea点击:

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

javastringloops

提问by enigma6174

Question

Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line. Assume input starts at index position 0(which is considered even)

给定一个长度为 N 的字符串 S,索引从 0 到 N-1,将它的偶数索引和奇数索引字符打印为 2 个空格分隔的字符串在一行上。假设输入从索引位置 0 开始(被认为是偶数)

Input

输入

The first line contains an integer, T (the number of test cases). Each line i of the T subsequent lines contain a String, S.

第一行包含一个整数 T(测试用例的数量)。后续 T 行中的每一行 i 都包含一个字符串 S。

Output

输出

For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.

对于每个字符串 S,打印它的偶数索引字符,然后是空格,然后是奇数索引字符。

Sample Input

样本输入

2

Hacker

Rank

2

黑客

Sample Output

样本输出

Hce akr

Rn ak

阿克尔

纳克

The Code I Wrote

我写的代码

public static void main(String[] args)
{
    Scanner scan    =   new Scanner(System.in);
    int T   =   scan.nextInt();
    scan.nextLine();

    for(int i=0 ; i<T ; i++)
    {
        String  myString    =   scan.nextLine();

        int evn =   0,
            odd =   0,
            len =   myString.length();

        char    strE[]  =   new char[50],
                strO[]  =   new char[50];

        for(int j=0 ; j<len ; j++)
        {
            if(j%2 == 0)
            {
                strE[evn]   =   myString.charAt(j);
                evn++;
            }
            if(j%2 == 1)
            {
                strO[odd]   =   myString.charAt(j);
                odd++;
            }
        }
        System.out.print(strE);
        System.out.print(" ");
        System.out.println(strO);
    }
}

My Output

我的输出

Hce akr

Rn ak

阿克尔

纳克

The Problem

问题

As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.

Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.

Could anyone please tell me where I am making a mistake?

如您所见,我的程序成功满足测试用例和其他测试用例(使用自定义输入)但每次 HackerRank 编译器告诉我我的程序不满足测试用例。

显然,我的程序正在生成所需的输出,但是每次 HackerRank 编译器告诉我我的解决方案是错误的。

谁能告诉我我在哪里犯了错误?

Further Modifications

进一步修改

I then decided to change the last 3 lines of print statements into one statement as follows:

然后我决定将打印语句的最后 3 行更改为一个语句,如下所示:

System.out.println(strE + " " + strO);

However, this time the program did notproduce the desired output and rather printed some garbage values as follows:

[C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610

但是,这次程序没有产生所需的输出,而是打印了一些垃圾值,如下所示:

[C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610

My Doubts

我的疑惑

1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?

2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?

1. 在第一种情况下,当我使用 2 个打印语句分别打印两个字符串时,我每次都得到正确的输出,但 HackerRank 编译器拒绝了它。为什么?

2. 在第二种情况下,当我通过使用一个打印语句而不是 3 个打印语句来修改程序以获得所需的结果时,该程序给出了完全不同的输出和打印的垃圾值!为什么?

Here is a link to the HackerRank problem for more info:hackerrank.com/challenges/30-review-loop

以下是 HackerRank 问题的链接以获取更多信息:hackerrank.com/challenges/30-review-loop

All help and guidance is greatly appreciated and thanks a lot in advance!

非常感谢所有帮助和指导,并在此先感谢!

采纳答案by Baji Ravella

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.

接下来,我们将创建一个名为“string”(顺便说一句,这是变量/对象的错误名称)的数组,其大小为 T,并且在 for 循环中从输入 T 次读取测试用例并将它们保存在数组中。

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).

我们创建了一个局部变量 j,它只在这个 for 循环中可见。j 保存我们正在处理的字符串 (=string[temp]) 的索引。所以,我们在位置 j 打印一个字符(通过使用 String 类的标准方法“charAt”,它返回字符串给定索引的字符),然后将其增加 2。因此,此代码将打印每个偶数字符。对于字符串“example”,它将打印“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. :)

我们正在做同样的事情(创建索引 j,运行字符串的所有字符),但是从“1”开始,所以它将打印字符串的所有奇数字符。对于字符串“example”,它会给你“xml”(j=1, j=3, j=5)。在此之后,它将结束字符串。我希望,它会帮助你理解。:)

回答by Velsson

I can solve your the second question: ---> System.out.print(strE);-->At the bottom, the method is called( public void print(char s[]));

我可以解决你的第二个问题:---> System.out.print(strE);-->在底部,方法被调用(public void print(char s[]));

-->System.out.println(strE + " " + strO);-->At the bottom, the method is called (public void println(String x) )

-->System.out.println(strE + " " + strO);-->在底部调用方法(public void println(String x))

回答by XtremeBaumer

Try to submit this:

尝试提交这个:

Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for (int i = 0; i < T; i++) {
    String myString = scan.nextLine();
    String even = "";
    String odd = "";
    for (int j = 0; j < myString.length(); j++) {
        if (j % 2 == 0) {
            even += myString.charAt(j);
        } else {
            odd += myString.charAt(j);
        }
    }

    System.out.println(even + " " + odd);
}

i get the right output and it should meet all the requirements. i think your code fails because its not a real string you print in the end and you have empty spots in your arrays

我得到了正确的输出,它应该满足所有要求。我认为你的代码失败了,因为它不是你最后打印的真正字符串,而且你的数组中有空点

回答by Dolf

For your first answer I am unable to answer you as I have no idea about how the compiler works, but I can answer your second question.

对于您的第一个答案,我无法回答您,因为我不知道编译器的工作原理,但我可以回答您的第二个问题。

The reason why System.out.print(strE); System.out.print(" "); System.out.println(strO);works is because System.out.print(char[])and System.out.println(char[])automatically turn the char arrays into a readable string before printing it.

为什么之所以System.out.print(strE); System.out.print(" "); System.out.println(strO);工作是因为System.out.print(char[])System.out.println(char[])自动开启的字符数组为易读的字符串在打印之前。

However, in the second case System.out.println(strE + " " + strO);, what you are doing is directly turning the char array into strings, which just prints the class and the hash code of the array object because the toString()method is not overriden in the array class. What you want to do is System.out.println(new String(strE) + " " + new String(strO));. It will give you the result you want.

但是,在第二种情况下System.out.println(strE + " " + strO);,您所做的是直接将char数组转换为字符串,它只是打印数组对象的类和哈希码,因为该toString()方法在数组类中没有被覆盖。你想要做的是System.out.println(new String(strE) + " " + new String(strO));。它会给你你想要的结果。

回答by Baji Ravella

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the no.of test-cases:");
    int t = scanner.nextInt();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the String(s)");
    for (int i = 0; i < t; i++) {

        String myString = br.readLine();
        String even = "";
        String odd = "";
        for (int j = 0; j < myString.length(); j++) {
            if (j % 2 == 0) {
                even += myString.charAt(j);
            } else {
                odd += myString.charAt(j);
            }
        }
        System.out.println(even);
        System.out.println(odd);
    }
    scanner.close();

回答by Raja Lakshmi

import java.io.*;
import java.util.*;

public class Solution {

 private static void f(String s) {
 // TODO Auto-generated method stub
  char c[]=s.toCharArray();
  int i,j;
  for (i = 0; i <c.length;i++){ 
      System.out.print(c[i]);
      i+=1;
  }
  System.out.print(" ");
  for (j = 1; j<c.length;j++){
     System.out.print(c[j]);
     j+=1;    
  }
 }
 public static void main(String[] args){
    // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    int s=sc.nextInt();
    while(hasNext()){
    //for loop for multiple strings as per the input
        for(int m=0;m<= s;m++){    
          String s1=sc.next();
          f(s1); 
          System.out.println();
        }
     }
   }
}

回答by Tushar Padihar

I've solved this question in 2 ways & both are producing correct output.

我已经通过两种方式解决了这个问题,并且都产生了正确的输出。

Have a look & let me know if you've any problem.

看一看,如果您有任何问题,请告诉我。

  1. Instead of using char array, you can use String

     //char[] even = new char[10000];
     String even = "";
    
  1. 您可以使用 String,而不是使用 char 数组

     //char[] even = new char[10000];
     String even = "";
    

Let's look at the code

我们看一下代码

private static Scanner scanner = new Scanner(System.in); 

public static void main(String[] args) {

        String s = scanner.next();

        char[] array = s.toCharArray();

        int count=0;            
        //char[] even = new char[10000];
        //char[] odd = new char[10000];
        String even = "";
        String odd = "";
        for(char ch : array){

            if(count%2 == 0){
                even = even + ch;
            }else{
                odd = odd + ch;
            }
            count++;
        }
        count = 0;

        System.out.println(even + " " + odd);
}

Output:

输出:

  hacker
  hce akr
  1. No need of extra char[] or String to store even & odd position characters, we can directly print them using appropriate condition.

    private static Scanner scanner = new Scanner(System.in); 
    
    public static void main(String[] args){
    
        String s = scanner.next();
    
        char[] array = s.toCharArray();
    
        int count=0;
    
        for(char ch : array){
    
            if(count%2 == 0){
                System.out.print(ch);
            }
            count++;
        }
        count = 0;
        System.out.print(" ");
        for(char ch : array){
    
            if(count%2 != 0){
                System.out.print(ch);
            }
            count++;
        }
        count = 0;
    }
    
  1. 不需要额外的 char[] 或 String 来存储偶数和奇数位置的字符,我们可以使用适当的条件直接打印它们。

    private static Scanner scanner = new Scanner(System.in); 
    
    public static void main(String[] args){
    
        String s = scanner.next();
    
        char[] array = s.toCharArray();
    
        int count=0;
    
        for(char ch : array){
    
            if(count%2 == 0){
                System.out.print(ch);
            }
            count++;
        }
        count = 0;
        System.out.print(" ");
        for(char ch : array){
    
            if(count%2 != 0){
                System.out.print(ch);
            }
            count++;
        }
        count = 0;
    }
    

Output:

输出:

  hacker
  hce akr

回答by Mayank Verma

Try this:

尝试这个:

public static void main(String[] args) {
    System.out.println("Enter string to check:");
    Scanner scan = new Scanner(System.in);
    String T = scan.nextLine();
    String even = "";
    String odd = "";
    for (int j = 0; j < T.length(); j++) {
        if (j % 2 == 0) { //check the position of the alphabet by dividing it by 0
            even += T.charAt(j);
        } else {
            odd += T.charAt(j);
        }
    }
    System.out.println(even + " " + odd);

    scan.close();
}

回答by Vikram Sapate

** JavaScript version **

function processData(input) {
   for (let i = 1; i < input.length; i++) {
     printOutput(input[i]);
   }
}

function printOutput(input) {
  var result = [];
  input.length % 2 == 0 ? result[input.length / 2] = ' ': result[Math.ceil(input.length / 2)] = ' ';
  for (let i = 0; i < input.length; i++) {
    if (i % 2 == 0) {
        result[i / 2] = input[i];
    }
    else {
        result[Math.ceil(input.length / 2) + Math.ceil(i / 2)] = input[i];
    }
}
console.log(result.join(''));
}

process.stdin.on("end", function () {
processData(_input.split('\n'));

});

回答by FuryCode

import java.io. * ;
import java.util. * ;

public class Solution {
String myString;
public Solution(String myString) {
    this.myString = myString;
    int len = myString.length();
    for (int j = 0; j < len; j++) {
        if (j % 2 == 0) {
            System.out.print(myString.charAt(j));
        }
    }
    System.out.print(" ");
    for (int j = 0; j < len; j++) {

        if (j % 2 == 1) {
            System.out.print(myString.charAt(j));
        }
    }
}
public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc = new Scanner(System. in );
    int T = sc.nextInt();
    for (int i = 0; i < T; i++) {
        String word = sc.next();
        Solution sol = new Solution(word);
        System.out.println();
    }
    sc.close();
}

}

}