Java 如何仅打印数组中的偶数或奇数字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18790309/
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 11:05:52  来源:igfitidea点击:

How do I print just the even or odd chars in an array?

javaarraysfor-loop

提问by Drieke

Lets say I have string: 'firetruck'. And I split that string up into the individual letters and put them into an array called T for example. So now T[] looks like {f,i,r,e,t,r,u,c,k}. How can I just print the even chars so my print statement looks like 'frtuk' and the odd looks like 'ierc'. This is what I got so far:

假设我有字符串:'救火车'。我将该字符串拆分为单个字母并将它们放入一个名为 T 的数组中。所以现在 T[] 看起来像 {f,i,r,e,t,r,u,c,k}。我怎么能只打印偶数字符,所以我的打印语句看起来像“frtuk”,而奇怪的看起来像“ierc”。这是我到目前为止得到的:

import java.util.Scanner;
import java.util.Arrays;
public class StringFun {

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

        //I can't get this next part to work.
        for(int i = t[0]; i < t.length; i = i + 2){
            System.out.println(Arrays.toString(t[i]));
        }
    }
}

采纳答案by ppeterka

Just a minor mistake in the code:

只是代码中的一个小错误:

You don't need the first value from the arrayto initialize the loop variable i, just the index valueyou want the loop to start from.

您不需要数组中第一个值来初始化循环变量i,只需要您希望循环开始的索引值

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 evenordinals will be printed when the start value is odd.

一个棘手的事情要记住的是,索引从0开始,但我们人类从1数(我没有在回答的第一个编辑这个错误太)因此与characterss甚至序将打印时起始值为奇数

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:

此外,您可以直接打印字符,这里不需要Arrays.toString()方法:

System.out.println(t[index]);

Is enough.

足够。

Odd chars:set ito 0: this will print the 1st, 3rd ... characters

奇数字符:设置i为 0:这将打印第一个、第三个...字符

       for(int i = 0; i < t.length; i = i + 2){
            System.out.println(t[i]);
        }

Even chars:set ito 1: this will print the 2nd, 4th ... chars

偶数字符:设置i为 1:这将打印第二个、第四个...字符

       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.charAt(int index)

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

Rememberduplication is bad. Reuse --> good.

记住重复是不好的重用 --> 好

回答by Habib

Start your loop with 0instead of t[0]

0而不是开始你的循环t[0]

 for(int i = 0; i < t.length; i = i + 2){

Currently iwill hold 102which is ASCII value of letter f, and it will not enter in the loop because of the condition.

当前i会保存102字母的ASCII值,f不会因为条件进入循环。

Why iwill hold a charvalue, for that see Widening primitive conversion - Javawhich allows

为什么i会持有一个char值,为此请参阅扩展原始转换 - Java允许

char to int, long, float, or double

char 到 int、long、float 或 double

回答by Ruchira Gayan Ranaweera

Try this

尝试这个

Odd

奇怪的

 char[] arr={'f','i','r','e','t','r','u','c','k'};
 for(int i=0;i<arr.length;i++){
     if(i%2==1){
         System.out.print(arr[i]);
     }
 }

Out put

输出

 ierc

Even

甚至

   char[] arr={'f','i','r','e','t','r','u','c','k'};
   for(int i=0;i<arr.length;i++){
    if(i%2==0){
     System.out.print(arr[i]);
     }
    }

Out put

输出

 frtuk

回答by StormeHawke

Pretty simple. Just put in an if(i % 2 == 0)to determine whether or not to print the character.

很简单。只需输入一个if(i % 2 == 0)以确定是否打印字符。

Also, there's no need for the Arrays.toString(t[i]). Change that to just t[i].

此外,也不需要Arrays.toString(t[i]). 将其更改为 just t[i]

回答by Aaron

Just a small error! You were close. This should fix it.

只是一个小错误!你很接近。这应该解决它。

 for(int i = 0; i < t.length; i = i + 2){

回答by OscarG

You have an error on the for statement, is not int i = t[0] but should be int i = 0; otherwise it will take the ASCII value of the character on the dirt position of the array.

你在 for 语句上有错误,不是 int i = t[0] 但应该是 int i = 0; 否则,它将采用数组污垢位置上字符的 ASCII 值。

回答by ThePerson

This will loop through your string and print out what you want.

这将遍历您的字符串并打印出您想要的内容。

 public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String even_odd = sc.next();

    System.out.println("Odd Characters");
    for(int i = 0; i<even_odd.length(); i++){
        if(i%2==0){
            System.out.println(even_odd.charAt(i));
        }   
    }

    System.out.println("Even Characters");
    for(int i = 0; i<even_odd.length(); i++){
        if(i%2==1){
            System.out.println(even_odd.charAt(i));
        }   
    }
}

回答by JustJ

Try This

尝试这个

public class char_odd_even {

    public static void main(String arg[]){

        Scanner sc = new Scanner(System.in);

        String s;
        s = sc.next();

        char char_array[];

        char_array=s.toCharArray();
        int a[] = new int[char_array.length];

        for(int i=0;i<char_array.length;i++)
        {
            a[i]=s.charAt(i);

            if(a[i]%2==0){
                System.out.println((char)a[i]+" EVEN CHAR " + a[i]);
            }
            else{
                System.out.println((char)a[i]+" ODD CHAR " + a[i]);
            }

        }

    }

}

回答by kanaparthikiran

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

导入 java.io。; 导入 java.util。;

public class Solution {

公共课解决方案{

/**
 * 
 * @param args
 */
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 scanner = new Scanner(System.in);
    int totalStrings = scanner.nextInt();

    String nextString = null;
    while(scanner.hasNext()) {
        nextString = scanner.next();
        int stringsCount = totalStrings;
        Solution stringInterleaving = new Solution();
        int startIndexEven=0,incrementEven=2;
        int startIndexOdd=1,incrementOdd=2;
         int printedCharCountEven = 0;
        int printedCharCountOdd = 0;
        if(nextString!=null && nextString.length()>0) {
             printedCharCountEven =
                stringInterleaving.printChars(nextString, startIndexEven,incrementEven);
               if(printedCharCountEven>0) {
                 System.out.print(" ");
               }
            printedCharCountOdd =
                stringInterleaving.printChars(nextString, startIndexOdd,incrementOdd);
        }
        if(printedCharCountEven>0 || printedCharCountOdd>0) {
                System.out.println();
        }
    }
    if(scanner!=null) {
        scanner.close();   
    }
}

    /**
 * 
 * @param input
 */
private int printChars(String input,int startIndex,int increment) {
        int printedCharCount = 0;
        if(input!=null && input.length()>0) {
            for(int i=startIndex;i<input.length();) {
               System.out.print(input.charAt(i));
                i=i+increment;
                printedCharCount++;
            }
        }  
    return printedCharCount;
}

}

}