How can I parse a String[] to an int[] in java? - string

I have the code:
String s = "a,b,c,d,e";
int[] i = s.split(",");
but this cast is not avaiable.
Some one can help me?
Thanks

You must loop over each element in the array and cast them one by one.
Like this:
String s = "a,b,c,d,e";
String[] strings = s.split(",");
int[] i = new int[strings.length];
for(int j = 0; j < strings.length; j++)
{
i[j] = Integer.parseInt(strings[j]);
}
Note that this code will crash, since the elements in the string-array aren't integers.

Java is strongly-typed which means it won't allow you to cast between incompatible types. In order to convert between integers and strings, you need to explicitly do the conversion. Integer.parseInt can convert a string to an integer. So you will need to loop through your array and convert each integer to a string individually.
String[] strings = "a,b,c,d,e".split(",");
int parsedIntegers[] = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
parsedIntegers[i] = Integer.parseInt(strings[i]);
}

Related

String Containing only Vowels

Suppose I have a vector of string and it contains strings (aei,ou,a). I want to concatenate them in O(n). After concatination it will become (aeiou,aeia,oua). I want to do concatination in one for loop. How to do it?
Mind you, I haven't checked this, i just made this on the fly. but this sounds like its what you want.
public void variableStrings(arr[] strings) {
List<string> newList = new List<string>();
for(int i = 0; i+1 < strings.Length -1; i++)
{
newList.add(string.Format("{0}{1}",strings[i],strings[i+1]));
}
}

c# beginner using stream reader to read in a txt file

i'm having trouble reading in a text file which contains 9 sets of three integer values separated by commas. This is what i have done so far, but how would i be able to read through the data going down row one to get a max value?
very stuck with a program the data text file looks like
21,7,11
20,10,12
17,7,18
these represent temperature, height and carbon%
i have read in the file as so
{
string s;
System.IO.StreamReader inputFile = new System.IO.StreamReader(DataFile);
s = inputFile.ReadLine();
int noDataLines = int.Parse(s);
double[,] data = new double[noDataLines, 3];
string[] ss;
is this right if the data is stored in the debug folder as a .txt file?
from here how would i go about getting a max temp(ie only reading the first vertical column of data)?
We can simply use mixture of System.IO File.ReadLines() method and LINQ .ToList() in order to read all text lines to List<string>. At this point we can just iterate through the collection parsing double values from text lines :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
{
string[] strValues = lines[i].Split(',');
for (int i2 = 0; i2 < strValues.Length; i2++)
temp[i2] = Convert.ToInt32(strValues[i2]);
values.Add(temp.ToArray());
}
Or we can use LINQ :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
values.Add(lines[i].Split(',')
.Select(l => Convert.ToInt32(l)).ToArray());

How to generate a random string between the strings contained in a vector?

Let's assume I have a vector of strings
vector<string> vec {"one", "two", "three", "four"};
string r;
I would like to have a random string (between the ones in vec) be generated and assigned to the string r.
How can I achieve this?
This is a very wide question, in terms of the amount of solution you can have and the amount of languages there are.
Lets talk generally, you can do something like that:
Random r = new Random();
for(int i=0; i < vec.lenght; i++)
{
number = r(0,vec.lenght-i);
string str = RemoveStringFromVectorAndShrinkIt(number);
r += str;
}

String/Array in Java

Does this work? I'm trying to print a message in this.
char[] tempMessage = message.toCharArray();
String[] message2 = message.split(" ");
Integer.toString(number).toCharArray();
for(int x = 0; x<newMessage.length; x++)
{
}
Although its better to use a StringBuilder, I can show it using String(s).
String[] strArr = "hello world".split("\\s+");
String s = String.valueOf(strArr[0].charAt(0))+strArr[0].length()+String.valueOf(strArr[1].charAt(0))+strArr[1].length();
Output : h5w5
String[] message2 = message.split("\\s+");
String output = "";
for(int i = 0; i < message2.length; i++)
{
output += "" + message2[i].charAt(0) + message2[i].length();
}
//output has output string.
TheLostMind's solution is already good, but I think it needs a solution for Strings of arbitrary length.
String outputString = "";
for(String x : message.split("\\s+"))
{
outputString = outputString.concat(x.charAt(0) + x.length());
}
As stated in the comments, this solution is very similiar to brso05's solution. The difference is in using the :-Operator in the for-loop. It's shorter and IMHO easier to understand, as it says 'for each String in the resulting array'.
Also, using the concat()-function is considered safer in my work environment.

Longest Common Subsequence for a series of strings

For the Longest Common Subsequence of 2 Strings I have found plenty examples online and I believe that I understand the solution.
What I don't understand is, what is the proper way to apply this problem for N Strings? Is the same solution somehow applied? How? Is the solution different? What?
This problem becomes NP-hard when input has arbitrary number of strings. This problem becomes tractable only when input has fixed number of strings. If input has k strings, we could apply the same DP technique in by using a k dimensional array to stored optimal solutions of sub-problems.
Reference: Longest common subsequence problem
To find the Longest Common Subsequence (LCS) of 2 strings A and B, you can traverse a 2-dimensional array diagonally like shown in the Link you posted. Every element in the array corresponds to the problem of finding the LCS of the substrings A' and B' (A cut by its row number, B cut by its column number). This problem can be solved by calculating the value of all elements in the array.
You must be certain that when you calculate the value of an array element, all sub-problems required to calculate that given value has already been solved. That is why you traverse the 2-dimensional array diagonally.
This solution can be scaled to finding the longest common subsequence between N strings, but this requires a general way to iterate an array of N dimensions such that any element is reached only when all sub-problems the element requires a solution to has been solved.
Instead of iterating the N-dimensional array in a special order, you can also solve the problem recursively. With recursion it is important to save the intermediate solutions, since many branches will require the same intermediate solutions. I have written a small example in C# that does this:
string lcs(string[] strings)
{
if (strings.Length == 0)
return "";
if (strings.Length == 1)
return strings[0];
int max = -1;
int cacheSize = 1;
for (int i = 0; i < strings.Length; i++)
{
cacheSize *= strings[i].Length;
if (strings[i].Length > max)
max = strings[i].Length;
}
string[] cache = new string[cacheSize];
int[] indexes = new int[strings.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = strings[i].Length - 1;
return lcsBack(strings, indexes, cache);
}
string lcsBack(string[] strings, int[] indexes, string[] cache)
{
for (int i = 0; i < indexes.Length; i++ )
if (indexes[i] == -1)
return "";
bool match = true;
for (int i = 1; i < indexes.Length; i++)
{
if (strings[0][indexes[0]] != strings[i][indexes[i]])
{
match = false;
break;
}
}
if (match)
{
int[] newIndexes = new int[indexes.Length];
for (int i = 0; i < indexes.Length; i++)
newIndexes[i] = indexes[i] - 1;
string result = lcsBack(strings, newIndexes, cache) + strings[0][indexes[0]];
cache[calcCachePos(indexes, strings)] = result;
return result;
}
else
{
string[] subStrings = new string[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
if (indexes[i] <= 0)
subStrings[i] = "";
else
{
int[] newIndexes = new int[indexes.Length];
for (int j = 0; j < indexes.Length; j++)
newIndexes[j] = indexes[j];
newIndexes[i]--;
int cachePos = calcCachePos(newIndexes, strings);
if (cache[cachePos] == null)
subStrings[i] = lcsBack(strings, newIndexes, cache);
else
subStrings[i] = cache[cachePos];
}
}
string longestString = "";
int longestLength = 0;
for (int i = 0; i < subStrings.Length; i++)
{
if (subStrings[i].Length > longestLength)
{
longestString = subStrings[i];
longestLength = longestString.Length;
}
}
cache[calcCachePos(indexes, strings)] = longestString;
return longestString;
}
}
int calcCachePos(int[] indexes, string[] strings)
{
int factor = 1;
int pos = 0;
for (int i = 0; i < indexes.Length; i++)
{
pos += indexes[i] * factor;
factor *= strings[i].Length;
}
return pos;
}
My code example can be optimized further. Many of the strings being cached are duplicates, and some are duplicates with just one additional character added. This uses more space than necessary when the input strings become large.
On input: "666222054263314443712", "5432127413542377777", "6664664565464057425"
The LCS returned is "54442"

Resources