简体   繁体   English

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

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

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.给定一个长度为 N 的字符串 S,索引从 0 到 N-1,将它的偶数索引和奇数索引字符打印为 2 个空格分隔的字符串在一行上。 Assume input starts at index position 0(which is considered even)假设输入从索引位置 0 开始(被认为是偶数)

Input输入

The first line contains an integer, T (the number of test cases).第一行包含一个整数 T(测试用例的数量)。 Each line i of the T subsequent lines contain a String, S.后续 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 2

Hacker黑客

Rank排名

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

Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.显然,我的程序正在生成所需的输出,但是每次 HackerRank 编译器告诉我我的解决方案是错误的。

Could anyone please tell me where I am making a mistake?谁能告诉我我在哪里犯了错误?

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 not produce the desired output and rather printed some garbage values as follows:但是,这次程序没有产生所需的输出,而是打印了一些垃圾值,如下所示:

[C@5c3f3b9b [C@3b626c6d [C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610 [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. 1. 在第一种情况下,当我使用 2 个打印语句分别打印两个字符串时,我每次都得到正确的输出,但 HackerRank 编译器拒绝了它。 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! 2. 在第二种情况下,当我通过使用一个打印语句而不是 3 个打印语句来修改程序以获得所需的结果时,该程序给出了完全不同的输出和打印的垃圾值! Why?为什么?

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!非常感谢所有帮助和指导,并在此先感谢!

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我认为你的代码失败了,因为它不是你最后打印的真正字符串,而且你的数组中有空点

    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();

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

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); System.out.print(strE); System.out.print(" "); System.out.println(strO);的原因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(char[])System.out.println(char[])在打印之前自动将字符数组转换为可读字符串。

However, in the second case System.out.println(strE + " " + strO);然而,在第二种情况下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. ,你所做的是直接将char数组转成字符串,它只是打印数组对象的类和哈希码,因为toString()方法在数组类中没有被覆盖。 What you want to do is System.out.println(new String(strE) + " " + new String(strO));你想要做的是System.out.println(new String(strE) + " " + new String(strO)); . . It will give you the result you want.它会给你你想要的结果。

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,它只在这个 for 循环中可见。 j holds index of the string (=string[temp]), which we're processing. j 保存我们正在处理的字符串 (=string[temp]) 的索引。 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.所以,我们在位置 j 打印一个字符(通过使用 String 类的标准方法“charAt”,它返回字符串给定索引的字符),然后将其增加 2。因此,此代码将打印每个偶数字符。 For string "example", it will print "eape" (j=0, j=2, j=4, j=6).对于字符串“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.我们正在做同样的事情(创建索引 j,运行字符串的所有字符),但是从“1”开始,所以它将打印字符串的所有奇数字符。 For string "example", it will give you "xml" (j=1, j=3, j=5).对于字符串“example”,它会给你“xml”(j=1, j=3, j=5)。 and After this, it will end the string.在此之后,它将结束字符串。 I hope, it will help you to understand.我希望,它会帮助你理解。 :) :)

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();
        }
     }
   }
}

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您可以使用 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.不需要额外的 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

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();
}
** 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'));

});
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();
}

} }

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

public class Solution {

    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
        int T;
        T = s.nextInt();
        String[] str = new String[T];
        int i;
        for(i=0;i<T;i++) {
            str[i] = s.next();
        }    
        for(i=0;i<T;i++) {
            char[] even = new char[5000];
            char[] odd = new char[5000];
            int ev =0,od=0;
            for(int j= 0;j< str[i].length();j++) {
                if(j%2== 0) {
                    even[ev] = str[i].charAt(j);
                    ev++;
                }else {
                    odd[od] = str[i].charAt(j);
                    od++;
                }
            }
            String strEven = new String(even);
            String strOdd = new String(odd);
           System.out.print(strEven.trim());
           System.out.print(" ");
           System.out.println(strOdd.trim());

        }
        s.close();
    }
}

I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array我相信这会起作用您忘记将其转换为字符串并增加字符数组的大小

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

public class Solution {

    public static void main(String[] args) {
        Scanner scan= new Scanner(System.in);
        int n= scan.nextInt();
        for(int i=0;i<n;i++){
            String s= scan.next();
            int len= s.length();
            StringBuffer str_e= new StringBuffer();
            StringBuffer str_o= new StringBuffer();
            for(int j=0;j<len;j++){
                if(j%2==0)
                    str_e= str_e.append(s.charAt(j));
                if(j%2==1)
                    str_o= str_o.append(s.charAt(j));
            }
            System.out.println(str_e+" "+str_o);
        }
    }
}

Try this:尝试这个:

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

public class Solution {

    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 pp=new Scanner(System.in);
        int n=pp.nextInt();

        for(int i=0; i<n; i++)
        {
            String ip=pp.next();
            String re1="",
                    re2="";
            for(int j=0; j<ip.length(); j++)
            {
                if(j%2 == 0)
                {
                    re1+= ip.charAt(j);
                }
                if(j%2 == 1)
                {
                    re2+= ip.charAt(j);        
                }
            }
              System.out.print(re1+" "+re2);     
            System.out.println("");    
        }
    }
}
public class PrintCharacters{

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    
    int noOfTestCases = sc.nextInt();
    sc.nextLine();
    String []inputStrings= new String[noOfTestCases];
    for(int i=0;i<noOfTestCases;i++) {
        inputStrings[i]=sc.nextLine();
    }
    
    for(String str: inputStrings) {
        String even ="";
        String odd ="";
        for(int i=0;i<str.length();i++) {
            if(i%2==0) {
                even+=str.charAt(i);
            }else {
                odd+=str.charAt(i);
            }
        }
        System.out.println(even+" "+odd);
    }
    sc.close();
    
}

}


Input: 
  2
  Hacker
  Rank

Output:
  Hce akr
  Rn ak

import java.util.*;导入 java.util.*;

public class Solution {公共课解决方案{

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 scan=new Scanner(System.in);
    int n=scan.nextInt();
    while(n>0) {
        String str=scan.next();
        for(int i=0;i<str.length();i++) {
            if(i%2==0) {
                System.out.print(str.charAt(i));
            }
        }
        System.out.print(" ");
        for(int i=0;i<str.length();i++) {
            if(i%2==1) {
                System.out.print(str.charAt(i));
            }
        }
        n--;
        System.out.println();
    }
    
    
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM