So I'm new to java and decided to mess around a little, I wrote a class that converts a string to an array made out of the ascii values of the characters in the string, but I don't know how to get the value of the variable i. I know it's easier to use a list but I'm really curious how to make this work. This is the code:
public class ToAscii {
static int[] toAscii(String txt){
int[] array = new int[1000];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch -1;
i++;
}
return array;
}
}
The problem with your code is ch -1 which should be just ch.
You should do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt){
int[] array = new int[txt.length()];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch;
i++;
}
return array;
}
}
Output:
[97, 66, 99]
Alternatively, you can do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt) {
int[] array = new int[txt.length()];
char[] ascii1 = txt.toCharArray();
for (int i = 0; i < array.length; i++) {
array[i] = ascii1[i];
}
return array;
}
}
Output:
[97, 66, 99]
txt.codePoints().toArray() will convert the String to codepoints (ie numbers of the characters).
For example:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
System.out.println(Arrays.toString("abc".codePoints().toArray()));
}
}
will print:
[97, 98, 99]
where 97 corresponds to 'a', 98 to 'b' and 99 to 'c'.
Related
I am stuck with this challenge, any help would be great.
'Create a function that takes both a string and an array of numbers as arguments. Rearrange the letters in the string to be in the order specified by the index numbers. Return the "remixed" string. Examples
remix("abcd", [0, 3, 1, 2]) ➞ "acdb"'
My attempt -
package edabitChallenges;
//Create a function that takes both a string and an array of numbers as arguments.
//Rearrange the letters in the string to be in the order specified by the index numbers.
//Return the "remixed" string.
public class RemixTheString {
public static String remix(String word, int[] array) {
char[] wordArray = word.toCharArray();
for (int i = 0; i < array.length; i++) {
char ch = ' ';
ch = wordArray[i];
wordArray[i] = wordArray[array[i]];
wordArray[array[i]] = ch;
}
String newString = new String(wordArray);
return newString;
}
public static void main(String[] args) {
System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));
}
}
I would suggest just iterating the indices passed in the array[] input, and then building out the output string:
public static String remix(String word, int[] array) {
char[] wordArray = word.toCharArray();
StringBuilder output = new StringBuilder();
for (int i=0; i < array.length; i++) {
output.append(wordArray[array[i]]);
}
return output.toString();
}
public static void main(String[] args) {
System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 })); // adbc
}
Here we use StringBuilder which exposes a handy append(char) method for adding one character at a time to the string in progress.
I have an input String of "0102030405" how can I split this number by two so that it would have an output of String[] ("01", "02", "03", "04", "05").
Try this,
String a = "0102030405";
System.out.println(Arrays.toString(a.split("(?<=\\G.{2})")));
String input = "0102030405";
String[] output = new String[input.length()/2];
int k=0;
for(int i=0;i<input.length();i+=2){
output[k++] = input.substring(i, i+2);
}
for(String s:output){
System.out.println(s);
}
You could try something like reading each two characters from a string.
This could be solved by: "(?<=\\G.{2})"
But I think a cleaner solution is this:
string.substring(startStringInt, endStringInt);
Here is a complete example:
package Main;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : splitString("0102030405", 2)) {
System.out.println(part);
}
}
private static List<String> splitString(String string, int numberOfChars) {
List<String> result = new ArrayList<String>();
for (int i = 0; i < string.length(); i += numberOfChars)
{
result.add(string.substring(i, Math.min(string.length(), i + numberOfChars)));
}
return result;
}
}
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
HelloWorld h1 = new HelloWorld();
String a = "0102030405";
System.out.println(h1.getSplitString(a));
}
private ArrayList<String> getSplitString(String stringToBeSplitted) {
char[] charArray = stringToBeSplitted.toCharArray();
int stringLength = charArray.length;
ArrayList<String> outPutArray = new ArrayList<String>();
for(int i=0; i <= stringLength-2; i+=2){
outPutArray.add("" + charArray[i] + charArray[i+1]);
}
return outPutArray;
}
}
Here the String is first split into a char array. Then using a for loop two digits are concatenated and put into a ArrayList to return. If you need an Array to return you can change the return type to String[] and in the return statement change it to
outPutArray.toArray(new String[outPutArray.size()];
If you insert a string has odd number of characters last character will be omitted. Change the loop condition to fix that.
I'm currently doing an activity that requires me to write this:
Write a definition for a static method stringHeads that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
My code is currently something like this:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p)
e = b - 1
for (int de = 0; rad.length > de; de++)
rad[de] = s.substring(0,e);
for (String str : rad)
return str;
}
//Just ignore the rest
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon"
stringHeads(a,b)
The output should be "Rado" , "Ra", "Rad", "Ra", "".
The error that I'm currently getting is that String cannot be converted to String[].
Basically my question is how to fix this error and if a better code can be written.
Three things:
e would be constant if you enter the second loop.
e could be larger than s.length() - you didn't handle this case.
You return a String instead of a String[]
And please always use braces if you use loops, even if the loop only contains one statement. It is much more readable and can avoid errors.
I think you will have to rethink your whole function. Don't know if it would be helpful to write the function for you.
Hints:
Write only one loop!
String[] rad = new String[p.length];
for (int i=0; i < p.length; i++) {
if (s.length() < ??) {
rad[i] = s.substring(0,??);
} else {
??
}
}
return rad;
I hope this will help you to get the answer yourself.
See my code below hope it helps:-
I provided the comments instead of explaining it in paragraph.
As for your error, you are returning String from method but expected is an array of String.
public static void main(String[] args){
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] output=stringHeads(a,b);
for(String s:output){
System.out.println(s);
}
}
Your method can be like below:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
//Iterate over integer array
for(int index=0; index<p.length; index++){
//Extracting the integer value from array one by one
e=p[index];
//If integer value is greater than String length
if(e>s.length()){
//Put the entire String in String array
rad[index]=s;
}else{
//Put the Substring value with range 0 to e i.e. integer value
rad[index]=s.substring(0,e);
}
}
return rad;
}
You could simplify you code by just using a single iteration with an alternative variable.
public static void main (String[] args) throws java.lang.Exception
{
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] result = stringHeads(a,b);
for(String x : result) System.out.println(x);
//Or you can write a separate display method instead.
}
public static String[] stringHeads(int[] p, String s)
{
String[] rad = new String[p.length];
//Use this variable for array allocation/iteration.
int i=0;
//Simply iterate using this for-each loop.
// This takes care of array allocation/ substring creation.
for (int x : p)
rad[i++] = s.substring(0,x);
return rad;
}
Please check the code below
public static String[] stringHeads(int[] intArray, String str) {
String[] result = new String[intArray.length];
int count=0;
for (int intValue : intArray)
{
result[count] = str.substring(0,intValue);
count++;
}
return result;
} //Just ignore the rest
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] strArray=stringHeads(a,b);
int count=0;
for(String str:strArray)
System.out.println(++count+"" +str);
}
Change your method like this
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
rad[e] = s.substring(0, b);
e++;
}
return rad;
}
For use this method
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0};
String b = "Radon";
String[] stringHeads = stringHeads(a, b);
for (String stringHead : stringHeads) {
System.out.println(stringHead);
}
}
Output is
Rado
Ra
Rad
Ra
There is no need for the for loop that iterates through the integer array p
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
for (int de = 0; de < p.length; de++){
if (p[de] < s.length())
rad[de] = s.substring(0,p[de]);
else
rad[de]=s;
}
return rad;
}
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
if(b<=s.length()){
rad[e] = s.substring(0, b);
}
e++;
}
return rad;
}
I'm trying to do some basics concerning an array of elements, specifically characters. My question is, how do I get the program to print my changes one by one? for example (I do not want my output going from "moon" to "mOOn" in one instance, but from "moon" to "mOon" to "mOOn", like that. Here is my code.
import java.util.*;
public class Practice
{
public static void main(String[] args)
{
String array[] = {"uuuuuuuupppppppssssssssss"};
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] = array[i].replace('p', 'P'));
//trying to print each change here
}
}
}
Thanks again!
EDIT/Update: I got the output to get the loop right, but the output is still not what I want (basically output: uPPPPPPS, uPPPPPPs, uPPPPPs, etc until the length of p ends). Any hints on what I could do? Thanks!
public static void main(String[] args){
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
char[] chars = array.toCharArray(): //converted
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'p') {
System.out.println(array.replace('p', 'P'));
}
}
}
public static void main(String[] args)
{
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
while ( array.contains("p") )
{
array = array.replaceFirst("p", "P");
System.out.println(array);
}
}
This is my homework, I am trying to get the occurrences of 'e' in strings of the array.
My method doesn't seem to work. Can anyone wise person advise where did I go wrong?
import java.util.*;
import java.lang.*;
import java.io.*;
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism", "dictated", "dodged", "cats and dogs"};
int result = numberOfCharacters(strings, 'e');
System.out.println("No. of occurrences of 'e' is " + result);
}
public static String numberOfCharacters(String str, char a) {
int aresult = 0;
if (str.length() > 0) {
aresult = count(str.substring(1), a) + (str.charAt(0) == a ? 1 : 0);
}
return aresult;
}
}
Just change your method signature to:
public static String numberOfCharacters(String[] str, char a) {
///code
}
+1 for santosh's answer. I have tried it in following way . Try it out
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism",
"eeeee", "dodged", "cats and dogs"};
int result = 0;
for(int i=0;i<strings.length;i++) {
result += numberOfCharacters(strings[i], 'e');
}
System.out.println("No. of occurrences of 'e' in String is "+ result);
}
public static int numberOfCharacters(String str, char a) {
int counter = 0;
for( int i=0; i<str.length(); i++ ) {
if( str.charAt(i)== a ) {
counter++;
}
}
return counter;
}
}
In one liner:
Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();
Where 'a' is the char and 'strArray' the array of strings.
Using idea on how to count chars in a String from this question:
Java: How do I count the number of occurrences of a char in a String?
Complete code:
import java.util.Arrays;
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism",
"eeeee", "dodged", "cats and dogs"};
System.out.println("No. of occurrences of 'e' is " +
countCharsInArray(strings, 'e'));
}
public static int countCharsInArray(String strArray[], char a) {
return Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();
}
}
Explaining it:
'Arrays.toString(strArray)' converts the array into a single string.
'replaceAll("[^"+a+"]", "")' replace all characters that are not the one we want by empty char '',
After that we only need to check the length of the resulting string.
Note: The array should not have nulls, or they should be removed first.