Java parse characters in array

string to char array java
how to declare char array in java
string to char java
string to array java
string to char array c#
string to char array in java 8
string to char array c++
string to char list java

Thanks for checking out my question. Edits were to expend.

This code takes the string "3$ 29C 3P 1H" and splits it into an array and prints. I want to parse each token of the array for the character and print as such: "3 dollars 29 cents 3 penny 1 hpenny" The idea is that the program can take any currency input and present it in "full" form.

public parseCurrency()
    {
        System.out.print('\u000c');
        String currencyIn = "3$ 29C 3P 1H";
        String[] tokens = currencyIn.split(" ");

        for (String t : tokens)
            { System.out.println(t);}

        String dollars = tokens[0];
        String cents = tokens[1];
        String penny = tokens [2];
        String hPenny = tokens [3];
    }

I think something like this needs to follow. The loop goes through the array, character by character, picks out the d, c, p, and h then replaces the characters with the corresponding strings.

for (int i=0; i<tokens.length(); i++)
    { 
        char c = tokens.charAt(i); 
        if (c == 'D')
            { 
            String dollarsFull = dollars.replaceAll("D", "Dollars");
        }
        if (c == 'C')
            {
            String centsFull = cents.replaceAll("C", "cents");
        }
     etc  
    } 

Question 1: The loop condition "tokens.length" is supposed to be the number of characters in each part of the array. I know my code is incorrect, but I don't understand why.

Question 2: I've used charAt() to parse characters in a string, does this line work the same way?

edits - I left this stuff out to keep the question light weight

The program is supposed to take user input with scanner so there is also supposed to be error detection. I took my current code out to make it quicker to read etc. I've seen examples with error detection parse a string and have a series of if statements (or switch) with error returns. For example, if the user inputs "3 29c 3p 1h" then the program will return something like "expected 'D'".

Many thanks in advance.

1.) charAt() is a method of String class (comes from CharSequence so available in it implementations )so you can only use it with strings like tokens[0].charAt(i);

2.) replaceAll takes String which are case sensitive so this cents.replaceAll("C", "cents") is different from cents.replaceAll("c", "cents")

or you can use replace rather than regex as

    System.out.print('\u000c');
    String currencyIn = "3$ 29C 3P 1H".replace("$"," Dollar")
                        .replace("C"," Cents");
                        // and so on
    String[] tokens = currencyIn.split(" ");

    String dollars = tokens[0]; // 3 Dollar
    String cents = tokens[1]; // 29 Cents
    String penny = tokens [2];
    String hPenny = tokens [3];

String to char array java - convert string to char, 1.) charAt() is a method of String class (comes from CharSequence so available in it implementations )so you can only use it with strings like  Given a string, the task is to convert this string into a character array in Java. Examples: Method 1: Naive Approach Step 1: Get the string. Step 2: Create a character array of the same length as of string.

You don't need a loop here. You can simply use replace method. Each replace method call returns a new String after replacing the target (D, C, P, H here) with the replacement string.

System.out.println(currencyIn.replace("D", " Dollars")
            .replace("C", " Cents")
            .replace("P", " Penny")
            .replace("H", " HPenny"));

Java parse characters in array, The simplest way to convert String to Char Array. How to convert String to Char Array in Java? Java Code: package com.crunchify;  How to convert byte array to String in Java. The process of converting a byte array to a String is called decoding. This process requires a Charset. Though, we should use charset for decoding a byte array. There are two ways to convert byte array to String: By using String class constructor; By using UTF-8 encoding; By using String Class Constructor

Instead of

    String dollars = tokens[0];
    String cents = tokens[1];
    String penny = tokens[2];
    String hPenny = tokens[3];

Try this instead:

    String dollars = tokens[0].replaceAll("D", "Dollars");
    String cents = tokens[1].replaceAll("C", "cents");
    ...

To answer your specific questions, it looks like you want to loop over characters in a string to find the characters to replace. But instead you're looping over tokens in the tokens array. Remember that tokens is defined to be a String[] so you can't call .charAt(i). You can only call .charAt() on a String object:

for (String token : tokens) {
    for (int i = 0; i < token.length(); i++) {
        char c = token.charAt(i);
        ...
    }
}

But this approach isn't necessary, using .replaceAll will accomplish what you want without you needing to write a loop.

Java: Simple way to convert String to Char Array • Crunchify, ArrayList;. import java.util.List;. // Convert a String to a List of Characters. class Util​. {. public static void main(String[] args). {. String string = "Techie Delight";. Java: Two ways to Convert Char Array to String ; Java: How to convert Byte[] Array To String ; In Java best way to Convert File into a Bytes (Array of Bytes) Best way to convert Primitive Array to List in Java8 and Classic toString(), Iterator way ; Java: Given a Non-Empty String Like -Code- Return a String Like -CCoCodCode-

try this :

public static String parseCurrency(String s)
{
    return s.replaceAll("\\$", " Dollars").replaceAll("C", " cents").replaceAll("P", " penny").replaceAll("H", " hpenny");
}

and you call :

String s = "3$ 29C 3P";
System.out.println(parseCurrency(s));

Please note that "$" is a special character, use "\$" instead of only "$" when you use replaceAll

Convert a String to a List of Characters in Java, In this post, we will see how to convert a String to Character array in Java. 1. Naive Solution.. 2. Using Java 8 3. Using Apache Commons Lang.. 4. Guava. Java Char Array Size or Length. This was actually shown in previous example, but below is a sample way if we want to know the length of an existing char array. char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'}; System.out.println(thisIsACharArray.length); This will output 5 as this is the number of items in the array. 5 Java Char Array Sorting

The easiest way to do this would be like this:

String currencyIn = "3$ 29C 3P 1H".toUpperCase();
currencyIn = currencyIn.replaceAll("$","dollar").replaceAll("C","cents").replaceAll("P","penny ").replaceAll("H","hpenny");

The code will get the string an change all the lowercase characters to uppercase.You can also change all the uppercase to lowercase using:

currencyIn.toLowerCase();

For the questions part:

1) tokens.length is showing the length of an array not the lengths of each item in the array.

2) charAt() is only used in strings.For arrays you use [index] and it will give you the object at the the index position.Be aware that you start from zero in arrays.

Convert a String to Character array in Java, There are two ways to convert a char array (char[]) to String in Java: 1) Creating String object by passing array name to the constructor 2) Using. String and Character Array. String is a sequence of characters that is treated as a single data item and terminated by null character '\0'. Remember that C language does not support strings as a data type. A string is actually one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.

How to convert a char array to a string in Java?, Java String toCharArray() method with method signature and examples of touppercase, tolowercase, trim, length, equals, split, string tochararray in java etc. The java string toCharArray() method converts this string into character array. The end result can be an array of characters or an array of Strings which contain characters. Below are the introduction and the method to solve the problem-Given a string, the task here is to break the string into characters. A String is a sequence of characters. But unlike C++, Strings in Java are not mutable.

Java String toCharArray() method, Strings in Java can be parsed using the split method of the String class. be treated as one. the split method returns an array containing the tokens (as strings​). The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string. The returned array length is equal to the length of the string.

Parsing Strings with split, Output p a s s w o r d 1 2 3. Java 8 – Convert String to Stream Char. For Java 8, you can uses .chars() to get the IntStream , and convert it to  The Java platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).

Comments
  • Assuming that both pieces of code are within same scope: 1. tokens.length gives you length of array (in your case it would be 4) and not the length of string. 2. tokens.charAt(i); this would not event compile since charAt is a method of String class, and is not applicable to array
  • please select one of the answers, if they are useful and does what you need. new users always do tend to forget they should select an answer if useful, or comment on them if they deviate from your needs.
  • iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
  • @YılmazDurmaz yes, but in this case, then the other option is break the string first then apply the replace using charAt and conditional statment
  • iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
  • @YılmazDurmaz From the requirement of the OP, it follows that the input would always be in a specific format.
  • iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
  • iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.