How to convert a String array to char array in Java - java

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings
For example:
Input: [i, love, you]
output: [i, l, o, v, e, y, o, u]
First I made an array of arrays.
Then I have found the length of the required char[] array.
I have tried the following so far:
char[][] a1 = new char[str.length][];
for(int i =0;i<str.length;i++){
a1[i]=str[i].toCharArray();
}
int total=0;
for(int i =0;i<str.length;i++){
total = total + a1[i].length;
}
char[] allchar = new char[total];
for(int i=0;i<str.length;i++){
//NOW HERE I WANT TO MERGE ALL THE char[] ARRAYS TOGETHER.
//HOW SHOULD I DO THIS?
}

String[] sArray = {"i", "love", "you"};
String s = "";
for (String n:sArray)
s+= n;
char[] c = s.toCharArray();

You can do that like this
char[] allchar = new char[total]; // Your code till here is proper
// Copying the contents of the 2d array to a new 1d array
int counter = 0; // Counter as the index of your allChar array
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
allchar[counter++] = a1[i][j]; // copying it to the new array
}
}

You can do something like the following method..
public void converter(String[] stringArray) {
char[] charsInArray = new char[500]; //set size of char array
int counterChars = 0;
for (int i = 0; i < stringArray.length; i++) {
int counterLetters = 0; //declare counter for for amount of letters in each string in the array
for (int j = 0; j < stringArray[i].length(); j++) {
// below pretty self explanatory extracting individual strings and a
charsInArray[counterChars] = stringArray[i].charAt(counterLetters);
counterLetters++;
counterChars++;
}
}
}

String [] s = new String[]{"i", "love", "you"};
int length = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
length++;
}
}
char [] c = new char[length];
int k = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
c[k] = s[i].charAt(j);
k++;
}
}
for (int j = 0; j < c.length; j++) {
System.out.print("char is: " + c[j]);
}

In Java 8 we can use streams.
public char[] convert(String[] words) {
return Arrays.stream(words)
.collect(Collectors.joining())
.toCharArray();
}
Here we created a stream from an array using
Array.stream(T[] array) where T is the type of the array elements.
Than we obtain a string using Collectors.joining(). Finally we get a char array using the String's toCharArray() method.

public static void main(String[] args)
{
String sentence="Gokul Krishna is class leader";
String[] array=sentence.split("\\s");
int counter;
//String word = new String();
for(String word:array)
{
counter=0;
char[] wordArray=word.toCharArray();
for(int i=0;i<wordArray.length;i++)
{
counter++;
}
System.out.println(word+ " :" +counter);
}
}

public char[] convert(String[] arr) {
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.toString().toCharArray();
}

Related

how to get String array containing distinct characters?

i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}
static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}
Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

java ", imcompatable types issue im having with my code: char cannot be converted to a string

For this java program I am taking in a string then printing/saving the string of characters in order of their frequency.
import java.util.*;
public class freqChar
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int myArray[] = new int[256];
int len = s.length();
String array1 [] = new String [len];
String strArray [] = new String [len];
for(int i = 0; i < s.length(); i++)
{
myArray[(int)s.charAt(i)]++;
}
for(int i = s.length(); i > 0; i--)
{
for(int j = 0; j < myArray.length; j++)
{
if(myArray[j] == i) // Here I am trying to fill a string array with the characters from the original string after I have casted them back from ints.
{
int g = 0;
char x = ((char)(j));
array1[g] = x;
g++;
}
}
}
for (int i = 0; i < len; i++)
{
System.out.println(array1[i] + " ");
}
}
}
When I compile it gives me the error:
cannot convert char to a string.
Short answer: a char is not a String so putting a char into an array of Strings won't work.
But its very easy to fix the problem, just replace char x =((char)(j)); with char x = Character.toString((char) j);

How to count same words in a string and get the index of the first word that is equal?

My task is to create a static method named "dupWords" that gets a strings as a parameter and returns how many times a word is at the same string. Now the catch is, that I need to return it as a Two-dimensional array, that have 2 columns and the rows will be how many different sub strings are in the string...
for example: "abcd xyz abcd abcd def xyz"
this will be the pairs [0][3] [5][2] [19][01] the first pair means that the word "abcd" appears 3 times and state at the index 0 (and you get the rest..)
this is an image of the two-dimensional array: (the text is in hebrew but you can see the drawing)
I started something...you will probably think its way off :/ (its just some start)
I think I didn't really understand how to deal with the two-dimensional array..
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
int [][] retArr;
for (int i = 0; i < stringArray.length; i++) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[i].equalsIgnoreCase(stringArray[j])){
countWords++;
index = stringArray[i].indexOf(str);
}
}
}
}
Please help,
thankss
Find the number of unique words.
You can do it, by putting all the words from the stringArray to a hashmap. The hashmap will come handy later.
Create an array like that retArr = new int[unique][2];
Complete solution below (beware, I didn't even compile it!)
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
int index = 0;
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
if (!indexMap .containsKey(s)) {
indexMap.put(s, index);
countMap.put(s, 1);
}
else {
int cnt = countMap.get(s);
countMap.put(s, cnt+1);
}
index += s.length() + 1;
}
int [][] retArr = new int[map.size()][2];
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
retArr[i][0] = indexMap.get(s);
retArr[i][1] = countMap.get(s);
}
return retArr;
}
Now, without HashMap, or any other dynamic structure it's quite difficult to do. The easiest approach is to create a bigger than necessary array and at the end trim it. This could look like this.
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
int [][] retArr = new int[stringArray.size()][2];
int uniqeWords = 0;
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
if (s != null) {
retArr[uniqueWords][0] = str.indexOf(s);
int cnt = 1;
for (int j = i + 1; j < stringArray.size(); j++) {
if (s.equalsIgnoreCase(stringArray[j])) {
stringArray[j] = null;
cnt++;
}
}
retArr[uniqueWords][1] = cnt;
uniqueWords++;
}
}
int[][] newRetArr = new int[uniqueWords][2];
for (int i = 0; i < uniqueWords; i++) {
newRetArr[i][0] = retArr[i][0];
newRetArr[i][1] = retArr[i][1];
}
return newRetArr;
}
Use a HashMap to store the count and first index of each unique word.
Map<String, Map<String, int>> uniqueWords = new HashMap<>();
Then Change your loop through stringArray to only use the first outer loop. You don't need the inner loop.
In each iteration through stringArray, do
if(!uniqueWords.get(stringArray[i])) {
uniqueWords.put(stringArray[i], new HashMap<String, int>());
uniqueWords.get(stringArray[i]).put("Count", 0);
uniqueWords.get(stringArray[i]).put("Index", str.indexOf(stringArray[i]));
}
uniqueWords.get(stringArray[i]).get("Count")++;
You can then use the uniqueWords map to build your return array. I'll leave that for you to code.

Java two-dimensional array of chars

I need to write a java program that has an array-returning method that takes a two-dimensional array of chars as a parameter and returns a single-dimensional array of Strings.
Here's what I have
import java.util.Scanner;
public class TwoDimArray {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Rows?");
int rows = s.nextInt();
System.out.println("Enter the number of Colums?");
int cols = s.nextInt();
int [][] array = new int [rows] [cols];
}
public static char[ ] toCharArray(String token) {
char[ ] NowString = new char[token.length( )];
for (int i = 0; i < token.length( ); i++) {
NowString[i] = token.charAt(i);
}
return NowString;
}
}
You need an array of String, not of chars:
public static String[] ToStringArray(int[][] array) {
String[] ret = new String[array.length];
for (int i = 0; i < array.length; i++) {
ret[i] = "";
for(int j = 0; j < array[i].length; j++) {
ret[i] += array[i][j];
}
}
return ret;
}
The above answers are right; however you may want to use StringBuilder class to build the string rather than using "+=" to concatenate each char in the char array.
Using "+=" is inefficient because string are immutable type in java, so every time you append a character, it will have to create a new copy of the string with the one character appended to the end. This becomes very inefficient if you are appending a long array of char.
public String[] twoDArrayToCharArray(char[][] charArray) {
String[] str = new String[charArray.length];
for(int i = 0; i < charArray.length; i++){
String temp = "";
for(int j = 0; j < charArray[i].length; j++){
temp += charArray[i][j];
}
str[i] = temp;
}
return str;
}

Categories

Resources