C# Java issue with String to Array to String - java

I am trying to convert a string to an array then back to a string again. I am trying to achieve this in C# but as i have not done C# in a while i am having issues. I created the following code in Java and it works fine:
String sHtml = "test1\r\ntest2\r\ntest3\r\ntest4\r\ntes5t\r\ntest6\r\ntest7\r\ntest8\r\ntest9\r\ntest10\r\ntest11\r\ntest12\r\ntest13\r\ntes14t\r\n";
int temp = 0;
List<String> emailText = new ArrayList<String>();
for(int x = 0; x<sHtml.length();x++){
if(sHtml.charAt(x)=='\n'){
emailText.add(sHtml.substring(temp, x));
temp = x;
}
}
String testingString="";
for(String words:emailText){
//System.out.println(words);
testingString+=words;
}
System.out.println(testingString);
This works fine in Java. The following code is what i have for C#:
int temp = 0;
List<string> emailText = new List<string>();
for (int x = 0; x < sHtml.Length; x++)
{
if (sHtml[x].Equals("\\n"))
{
emailText.Add(sHtml.Substring(temp, x));
temp = x;
}
else
{
}
}
string testingString = "";
//sHtml = string.Join("\r\n", emailText.ToArray());
foreach (String word in emailText)
{
testingString += word;
}
Console.WriteLine(testingString);
The java code outputs fine but i am getting no output from the C# code. I have a feeling i am missing something small from the C# code but i am not sure what, Can someone please help?
Thanks in advance

You don't get output in C# because you don't output anything :-) You omitted the Java System.out.println statement without adding the C# equivalent:
Console.WriteLine(testingString);
BTW: Once you're replacing your Java code by C# code, you can also make use of the .NET framework's features (as others already mentioned). This way you can reduce your program to one line:
Console.WriteLine(string.Join(string.Empty, sHtml.Split('\n')));

Try this: although i would recommend using a string builder for larger strings as they're immutable.
string yourString = "this,is,a,example,string";
string newString = "";
string[] array = yourString.Split(',');
foreach (string s in array)
{
newString += s;
}
Console.WriteLine(newString);

Why don't you use this to split the string:
string[] List = sHtml.split("\\n");
And this to do something with the arraylist of strings to do something:
for (String s in List){
//Do something with each separate String s
}

Why not use split and join?
var arr = str.Split('\n');
var newStr = string.Join("", arr);

Your 'for' loop has 2 mistakes - you should keep the character '\n' and Java 'substring' doesn't have the same second parameter that .NET 'Substring' has, so you need to adjust that:
for (int x = 0; x < sHtml.Length;x++)
{
if (sHtml[x] == '\n')
{
emailText.Add(sHtml.Substring(temp, x - temp));
temp = x;
}
}

Related

How to remove phrase from beginning to end

I've been trying for a while now, and I just give up. I want to extract the data from type (regardless whether it's a capital letter or not) to the numbers. Pretty much, I'm trying to get rid of model and birthday in each line, but what makes it even more difficult, is that it's all one string. I spaced it out just to make it easier to read.
I'm trying to find the answer in REGEX java. This is what I was trying but, is deleting of course the whole String after the first number(4,66)
[;][mo].*
Thank you in advance!
Input:
Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980
type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977
tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980
type:Carro;high:4,66;type:model;birthday:6/12/1887
type:Carro;high:9,66;model:Doors;birthday:05/12/2010
Expected OutPut:
Type:Carro;high:4,66
type:Truck;high:5,66
tYpe:motorcycle;high:1,55
type:Carro;high:4,66
type:Carro;high:9,66
Hopefully this will work for you. There are a few ways to make this code slightly smaller, however, this should at least help to get you on the right path.
I placed it into a main method, but it would be easy to put it into its own function. This would allow you to pass any number of arrays at it.
I added all of the logic in the comments within the code, I hope it helps:
public static void main(String[] args) {
/*Get your strings into an Array*/
String[] str = {"Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980",
"type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977",
"tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980",
"type:Carro;high:4,66;type:model;birthday:6/12/1887",
"type:Carro;high:9,66;model:Doors;birthday:05/12/2010",
"Expected OutPut:",
"Type:Carro;high:4,66",
"type:Truck;high:5,66",
"tYpe:motorcycle;high:1,55",
"type:Carro;high:4,66",
"type:Carro;high:9,66"
};
/*Create a "final staging" array*/
String[] newStr = new String[str.length - 1];
for (int j = 0; j < str.length - 1; j++) {//For each of your strings
str[j] = str[j].toLowerCase();//set the string to lower
/*If they don't contain a semi-colon and a model or birthday reference go to else*/
if (str[j].contains(";") && str[j].contains("model") || str[j].contains("birthday")) {
/*Otherwise, split the string by semi-colon*/
String[] sParts = str[j].split(";");
String newString = "";//the new string that will be created
for (int i = 0; i < sParts.length - 1; i++) {//for each part of the sParts array
if (sParts[i].contains("model") || sParts[i].contains("birthday")) {//if it contains what is not desired
//Do Nothing
} else {
newString += sParts[i];//otherwise concatenate it to the newString
}
newStr[j] = newString;//add the string to the "final staging" array
}
} else {
newStr[j] = str[j];//if it didn't have semi-colons and birthday or model, just add it to the "final staging" array
}
}
for (String newS : newStr) {// finally if you want to see the "final staging" array data... output it.
System.out.println(newS);
}
}
OUTPUT
type:carrohigh:4,66
type:truckhigh:5,66
type:motorcyclehigh:1,55
type:carrohigh:4,66
type:carrohigh:9,66
expected output:
type:carro;high:4,66
type:truck;high:5,66
type:motorcycle;high:1,55
type:carro;high:4,66
If I happened to miss something in the requirements, please let me know, I would be happy to fix it.
String str = "Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980,type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977,tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980,type:Carro;high:4,66;type:model;birthday:6/12/1887";
StringTokenizer tokens = new StringTokenizer(str, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken() ;
StringTokenizer tokens2 = new StringTokenizer(token, ":");
while (tokens2.hasMoreTokens()) {
String key = tokens2.nextToken() ;
if (key.equalsIgnoreCase("type")){
System.out.println("locate: "+key+"\n");
}
}
}

Using charAt() to change a char array

I'm utterly boggled as to why charAt() works in some scenarios but not others. I am doing exercises while learning Java and one of them was to take a string, and return it in reverse order.
My working code:
public String reverseString(String tempStr){
int initialindex = tempStr.length()-1;
int reverseindex = 0;
char tmp;
char[] array = new char[tempStr.length()];
for(int tempchar : array){
tmp = tempStr.charAt(initialindex);
array[reverseindex] = tmp;
initialindex--;
reverseindex++;
}
String returnstr = new String(array);
return returnstr;
}
The problem I ran into is using the following for statement prints gibberish:
for(int tempchar : array){
array[reverseindex] = tempStr.charAt(initialindex);
initialindex--;
reverseindex++;
}
There were perhaps a dozen different variants of using while loops, standard for loops and a few other versions of code that were ugly and didn't work. Why did my making a char tmp field, putting the inspected characrer in said field, and then using said field to enter the data into an array work?
Also, why am I unable to just return the string using return array.toString();?
Edit: I'm using the latest Eclipse I downloaded today, switched from netbeans.
I copied your code into my editor and it performed fine using either version, with tmp field or without. You must have made some other error using the other method.
Java doesn't support pretty .toString() for arrays; any object which does not override toString will produce the hashCode of the object rather than the contents/fields of the object, and arrays are no exception here. Whilst it might seem sensible for character arrays, the same operation on an int array would produce nonsense; See the difference between Arrays.toString() and String.valueOf(array). In this case, you probably want to use the String.valueOf method.
The array.toString() return string representation of the object. You need to use char[] constructor of String new String(array) to create String from the char[].
As a hint to get you started: if you want to convert a char array into a String use the String constructor that takes a char array.
Update: I see you already did that in your edit. Does it work as expected now?
Your loop looks a little bit weird since you never use your loop variable. you could try this:
char[] initialArray = initialStr.toCharArray();
char[] array = new char[tempStr.length()];
for(int srcIndex = 0, destIndex = array.length-1; destIndex >= 0; srcIndex++, destIndex--) {
array[destIndex] = initialArray[srcIndex];
}
public String reverse(String str)
{
if(str == null)
{
return null;
}
byte[] byteArray= str.getBytes();
int arrayLastIndex = byteArray.length -1 ;
for(int i=0 ; i < byteArray.lenght/2: i++)
{
byte temp = byteArray[i];
byteArray[i] = byteArray[arrayLastIndex -i ]
byteArray[arrayLastIndex - i] = temp;
}
return new String(byteArray);
}

Code optimization by chosing another datastructure

I have a piece of code that needs to be optimized.
for (int i = 0; i < wordLength; i++) {
for (int c = 0; c < alphabetLength; c++) {
if (alphabet[c] != x.word.charAt(i)) {
String res = WordList.Contains(x.word.substring(0,i) +
alphabet[c] +
x.word.substring(i+1));
if (res != null && WordList.MarkAsUsedIfUnused(res)) {
WordRec wr = new WordRec(res, x);
if (IsGoal(res)) return wr;
q.Put(wr);
}
}
}
Words are represented by string. The problem is that the code on line 4-6 creates to many string objects, because strings are immutable.
Which data structure should I change my word representation to, if I want to get faster code ? I have tried to change it to char[], but then I have problem with getting the following code work:
x.word.substring(0,i)
How to get subarray from a char[] ? And how to concatenate the char and char[] on line 4.6 ?
Is there any other suitable and mutable datastrucure that I can use ? I have thought of stringbuffer but can't find suitable operations on stringbuffers.
This function generates, given a specific word, all the word that differs by one character.
WordRec is just a class with a string representing a word, and a pointer to the "father" of that word.
Thanks in advance
You can reduce number of objects by using this approach:
StringBuilder tmp = new StringBuilder(wordLength);
tmp.append(x.word);
for (int i=...) {
for (int c=...) {
if (...) {
char old = tmp.charAt(i);
tmp.setCharAt(i, alphabet[c]);
String res = tmp.toString();
tmp.setCharAt(i, old);
...
}
}
}

Java loop not creating string correctly

I'm using a for loop to append an "m" on to a string array, then passing each string to a DDE connection to download a stock quote.
String[] symbols = {"AUDUSD", "EURUSD", "GBPUSD", "USDJPY"};
String ibfxSym[] = new String[symbols.length];
for(int i = 0; i<symbols.length;i++) {
ibfxSym[i] = symbols[i] + "m";
}
// start DDE
for (int i = 0; i < connections.length; i++) {
try {
connections[i].getQuote(ibfxSym[i]);
} catch (Exception e) {
System.out.println("error");
}
That does not work, but if I pass in:
String[] ibfxSym = {"AUDUSDm", "EURUSDm", "GBPUSDm", "USDJPYm"};
instead of the loop it works just fine. I've tried printing each string as it is created in the loop, and they look the same. Is there some weird formatting the loop is adding that I can't see? I even tried:
ibfxSym[i] = String.valueOf(ibfxSym[i].trim());
to see if there was maybe a carriage return or something being appended that I couldn't see. Any ideas about what's going wrong here?
Thanks.
You're not reading from the same array that you're modifying...
ibfxSym[i] = symbols[i] + "m";
for (int i = 0; i < connections.length; i++) {
try {
connections[i].getQuote(ibfxSym[i]);
In other words, you are assuming that i, being derived from iterating over connections, is also a valid index for ibfxSym.
Your loop is working just fine, the connection loop instead would work only if your connections array maps your ibfxSym array though..
if
connections.length
is bigger than
ibfxSym.length
or in this case 4, you should get an array index out of bounds exception i think.
Have you tried to do this:
for(int i = 0; i<symbols.length;i++) {
ibfxSym[i] = new String(symbols[i] + "m");
}

What's the most elegant way to concatenate a list of values with delimiter in Java?

I have never found a neat(er) way of doing the following.
Say I have a list/array of strings.
abc
def
ghi
jkl
And I want to concatenate them into a single string delimited by a comma as follows:
abc,def,ghi,jkl
In Java, if I write something like this (pardon the syntax),
String[] list = new String[] {"abc","def","ghi","jkl"};
String str = null;
for (String s : list)
{
str = str + s + "," ;
}
System.out.println(str);
I'll get
abc,def,ghi,jkl, //Notice the comma in the end
So I have to rewrite the above for loop as follows
...
for (int i = 0; i < list.length; i++)
{
str = str + list[i];
if (i != list.length - 1)
{
str = str + ",";
}
}
...
Can this be done in a more elegant way in Java?
I would certainly use a StringBuilder/Buffer for efficiency, but I wanted to illustrate the case in point without being too verbose. By elegant, I mean a solution that avoids the ugly(?) if check inside the loop.
Using Guava's (formerly google-collections) joiner class:
Joiner.on(",").join(list)
Done.
Here is my version: Java Tricks: Fastest Way to Collecting Objects in a String
StringBuilder buffer = new StringBuilder ();
String delim = "";
for (Object o: list)
{
buffer.append (delim);
delim = ", "; // Avoid if(); assignment is very fast!
buffer.append (o);
}
buffer.toString ();
As an additional bonus: If your code in the loop is more complex, then this approach will produce a correct results without complex if()s.
Also note that with modern CPUs, the assignment will happen only in the cache (or probably only in a register).
Conclusion: While this code looks odd at first glance, it has many advantages.
StringBuilder builder = new StringBuilder();
for (String st: list) {
builder.append(st).append(',');
}
builder.deleteCharAt(builder.length());
String result = builder.toString();
Do not use '+' for string contacenations. It`s slow.
Look here:
http://snippets.dzone.com/posts/show/91
for a full discussion of this topic.
I'd bet that there are several classes named "StringUtil", "StringsUtil", "Strings" or anything along those lines on the classpath of any medium sized Java project. Most likely, any of them will provide a join function. Here are some examples I've found in my project:
org.apache.commons.lang.StringUtils.join(...)
org.apache.wicket.util.string.Wicket.join(...)
org.compass.core.util.StringUtils.arrayToDelimitedString(...)
As you might want to get rid of some external dependencies in the future, you may want to to something like this:
public static final MyStringUtils {
private MyStringUtils() {}
public static String join(Object[] list, String delim) {
return org.apache.commons.lang.StringUtils.join(list, delim);
}
}
Now that's what I call "elegant" ;)
check if this is useful:
List<Integer> numbers=new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
String str = " ";
for(Integer s:numbers){
str=str+s+" , ";
}
System.out.println(str.substring(0,str.length()-2));
I would use a StringBuffer to implement this feature. String is immutable so everytime you concat two Strings, a new object is created.
More efficient is the use of StringBuffer:
String[] list = new String[] {"abc","def","ghi","jkl"};
StringBuffer str = new StringBuffer();
for (String s : list) {
str.append(s);
str.append(",");
}
str.deleteCharAt(str.length());
System.out.println(str); //automatically invokes StringBuffer.toString();
for (int i = 0; i < list.length-1; i++) {
str = str + list[i];
str = str + ",";
}
str = str + list[list.length-1]

Categories