Java add chars to a string - java

I have two strings in a java program, which I want to mix in a certain way to form two new strings. To do this I have to pick up some constituent chars from each string and add them to form the new strings. I have a code like this(this.eka and this.toka are the original strings):
String muutettu1 = new String();
String muutettu2 = new String();
muutettu1 += this.toka.charAt(0) + this.toka.charAt(1) + this.eka.substring(2);
muutettu2 += this.eka.charAt(0) + this.eka.charAt(1) + this.toka.substring(2);
System.out.println(muutettu1 + " " + muutettu2);
I'm getting numbers for the .charAt(x) parts, so how do I convert the chars to string?

StringBuilder builder = new StringBuilder();
builder
.append(this.toka.charAt(0))
.append(this.toka.charAt(1))
.append(this.toka.charAt(2))
.append(' ')
.append(this.eka.charAt(0))
.append(this.eka.charAt(1))
.append(this.eka.charAt(2));
System.out.println (builder.toString());

Just use always use substring() instead of charAt()
In this particular case, the values are mutable, consequently, we can use the built in String class method substring() to solve this problem (#see the example below):
Example specific to the OP's use case:
muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);
muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
Concept Example, (i.e Example showing the generalized approach to take when attempting to solve a problem using this concept)
muutettu1 += toka.substring(x,x+1) + toka.substring(y,y+1) + eka.substring(z);
muutettu2 += eka.substring(x,x+1) + eka.substring(y,y+1) + toka.substring(z);
"...Where x,y,z are the variables holding the positions from where to extract."

The obvious conversion method is Character.toString.
A better solution is:
String muutettu1 = toka.substring(0,2) + eka.substring(2);
String muutettu2 = eka.substring(0,2) + toka.substring(2);
You should create a method for this operation as it is redundant.
The string object instatiantiation new String() is unnecessary. When you append something to an empty string the result will be the appended content.

You can also convert an integer into a String representation in two ways: 1) String.valueOf(a) with a denoting an integer 2) Integer.toString(a)

This thing can adding a chars to the end of a string
StringBuilder strBind = new StringBuilder("Abcd");
strBind.append('E');
System.out.println("string = " + str);
//Output => AbcdE
str.append('f');
//Output => AbcdEf

Related

Two strings appear to be equal, but they are not

I want to open a file using the argument I get via a socket. When I extract the filename using split(), the file does not open. But when I hardcode the value, it does open.
What am I missing here? I would expect the strings to be equal.
String name = str.split(";")[2];
System.out.println("Filename: " + name);
String path1 = new String("Input_Blatt3/Sample.txt");
String path2 = new String("Input_Blatt3/" + name);
System.out.println("Path1: " + path1);
System.out.println("Path2: " + path2);
System.out.println("path1.equals(path2) = " + path1.equals(path2));
Output:
Path1: Input_Blatt3/Sample.txt
Path2: Input_Blatt3/Sample.txt
path1.equals(path2) = false
There could be unprintable characters hidden in the String.
Use getBytes to get all the characters of a String and print those. You'll probably find something you didn't expect.
You need to iterate over the byte array to print each byte individually, as in the following method:
private static void printBytes(String string) {
System.out.println("printing " + string);
for (byte aByte : string.getBytes()) {
System.out.println( aByte );
}
}
Alternatively you could also replace everything that isn't a printable character with nothing.
There could be some trailing white spaces, which you would not see at the console output.
You can try name.strip() (or trim() if your JDK version is lower 11) to ensure that there's nothing but the file name in the string.
Also, you can find the index of the first mismatching character of these two strings using Arrays.mismatch():
int indexOfMismatch = Arrays.mismatch(str1.toCharArray(), str2.toCharArray());
In case if the strings are equal, indexOfMismatch would be -1.

Get specific words from a string in Java

If I have the following URL:
http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0
How can I get the name of the plugin (simply named wordpressplugin in the URL) and the version so the output will be - wordpressplugin ver 1.0?
I am posting my comment as an answer
String s = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
String[] ary = s.split("/");
System.out.println(ary[5] + " " + ary[7]);
Easiest way this is acc to your question,
you have to use regex for more dynamic searching.
You may do it like so, using Regex support in Java.
String url = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
Pattern pattern = Pattern.compile("(.*plugins/)(.*)(/\\d{3}/)(ver.*)");
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
System.out.println("Plugin: " + matcher.group(2));
System.out.println("Version: " + matcher.group(4));
}
Notice the use of capture groups. Here's the output.
Plugin: wordpressplugin
Version: ver=1.0
You should have a look into Regular Expressions (in Oracle tutorials), which are the general tool in any programming language to get/match sub-strings out of a larger string (which follows some more or less fixed format).
Because you claim to be new to JAVA, here is a very simple answer that should suit your skills
String url = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
String search = "plugins/";
int index = url.indexOf(search);
String pluginName, version;
if (index > -1)
{
index += search.length;
pluginName = url.substring(index, url.indexOf("/",index + 1));
search = "ver=";
index = url.indexOf(search);
if (index > -1)
{
version = url.substring(index + search.length);
System.out.prinln(pluginName + " " + version);
}
}
PS: This would work if and only if your url format always remains the same!
The fastest way to solve this problem is to take advantage of the split method of Strings. Just study the method below carefully, it's basic.
public String getVersionNumber(String url){
String[] arr0 = url.split("//");
//The code above returns an array of two strings: "http:" and "www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0"
String[] arr1 = arr0[1].split("/");
//The code above returns an array of six strings: "www.example.com", "wordpress", "plugins", "wordpressplugin", "123" and "ver=1.0".
return String.format("%s %s", arr1[3], arr1[5]);
//OUTPUT: wordpressplugin ver=1.0
//I simply returned what I needed.
}
I hope this helps.. merry coding!

how to generate string with varying number of spaces OR how to add no of spaces after a string

I need help to generate empty string with particular no of spaces.
I tried this,
String opCode= " ";
for(int l=0;l<opCodelen;l++)
{
opCode+= " " ;
}
//opCodelen will get change every time
This worked but I want better solution.becoz using this I will have to use multiple loops for multiple columns.Is there any other way to do this?
Try String.format()
int opCodelen = 5;
String opCode = String.format("%" + opCodelen + "s", "");
System.out.println("[" + opCode + "]");
output
[ ]
Another way (uglier but for many probably simpler) to solve it could be
creating array of characters with same length as number of spaces you want to end up with,
filling it with spaces
and passing it as argument in String constructor.
Something like
char[] arr = new char[10]; // lets say length of string should be 10
Arrays.fill(arr, ' '); // fill array with spaces
String mySpaceString = new String(arr);
System.out.println(">" + mySpaceString + "<");
output:
> <

Insert a space after every given character - java

I need to insert a space after every given character in a string.
For example "abc.def..."
Needs to become "abc. def. . . "
So in this case the given character is the dot.
My search on google brought no answer to that question
I really should go and get some serious regex knowledge.
EDIT : ----------------------------------------------------------
String test = "0:;1:;";
test.replaceAll( "\\:", ": " );
System.out.println(test);
// output: 0:;1:;
// so didnt do anything
SOLUTION: -------------------------------------------------------
String test = "0:;1:;";
**test =** test.replaceAll( "\\:", ": " );
System.out.println(test);
You could use String.replaceAll():
String input = "abc.def...";
String result = input.replaceAll( "\\.", ". " );
// result will be "abc. def. . . "
Edit:
String test = "0:;1:;";
result = test.replaceAll( ":", ": " );
// result will be "0: ;1: ;" (test is still unmodified)
Edit:
As said in other answers, String.replace() is all you need for this simple substitution. Only if it's a regular expression (like you said in your question), you have to use String.replaceAll().
You can use replace.
text = text.replace(".", ". ");
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29
If you want a simple brute force technique. The following code will do it.
String input = "abc.def...";
StringBuilder output = new StringBuilder();
for(int i = 0; i < input.length; i++){
char c = input.getCharAt(i);
output.append(c);
output.append(" ");
}
return output.toString();

What does this NumberFormatException mean?

java.lang.NumberFormatException: For input string: ":"
What does this mean?
I get the above error if I run the code (below).I am a beginner here.
and..
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
the code:
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter")
Statement stm=con.createStatement();
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true){
m="m";}
if(jCheckBox2.isSelected()==true){
t="t";}
if(jCheckBox3.isSelected()==true){
w="w";}
if(jCheckBox4.isSelected()==true){
th="th";}
if(jCheckBox5.isSelected()==true){
f="f";}
if(jCheckBox6.isSelected()==true){
st="st";}
if(jCheckBox7.isSelected()==true){
s="s";}
runson= m + t + w + th + f + st + s ;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2)
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
Boolean x=jTextField10.getText().substring(2,3).equals(":");
Boolean y=jTextField12.getText().substring(2,3).equals(":");
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring (2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0){
tfac1="0";
if(Integer.valueOf(jTextField4.getText())==0){
tfac2="0";}
if(Integer.valueOf(jTextField5.getText())==0){
tfac3="0";}
if(Integer.valueOf(jTextField6.getText())==0){
tfsl="0";}
if(y==true&&x==true&&jTextField1.getText().trim().length()<=6&&jTextField2.getText().trim().length()<=30&&h1<=24&&h2<=24&&mins1<=59&&mins2<=59){
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+");";
stm.executeUpdate(q);
JOptionPane.showMessageDialog("ADDED");
}
}
catch (Exception e){
e.printStackTrace();
}
that means you can not convert the String ":" to Number like integer or double
see below link
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
According to java docs
Thrown to indicate that the application has attempted to convert a
string to one of the
numeric types, but that the string does not have the appropriate format.
It means you want to convert ":" to a number which is not allowed. Hence you are getting the exception. Better show your code
The best way you get responses faster & answered your question is posting your code.
You cannot convert String to number.
As others have said Java can't convert "15:" into a number because ":" is not a digit. And the most probable cause for this is a line like this one:
int h1 = Integer.valueOf(jTextField10.getText().substring(0,2));
where you are splitting a time string at the wrong index which is why you have ":" in it.
UPDATE
Better way of splitting a time string like "12:35:09" is by using String.split():
String timeString = "12:35:09";
String[] parts = timeString.split(":");
boolean validTimeString = parts.length == 3;
The code above will result in the following values:
timeString = "12:35:09"
parts[0] = "12"
parts[1] = "35"
parts[2] = "09"
validTimeString = true
String.split(DELIMITER) will split the string into N + 1 strings where N is the number of occurences of the DELIMITER in target string.

Categories

Resources