Concat the two first characters of string - java

I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?

You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring

What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.

String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);

Related

Wrong Answer with Java

I'm a student that is learning Java, and I have this code:
lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres is a string, and it's like this
lletres = "BBB"
The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".
Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.:
lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);
As others pointed replace() will replace all the occurrences which matched.
So, instead you can make use of replaceFirst() which will accept the regx
lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )
You could use StringBuilder for your purpose:
String lletres = "BBB";
String codi = "CCC";
StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();
If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.
String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);
This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.
Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.
With slight modification you can get it to replace whole parts of the string, not only letters. :)
Try this one.
class Rplce
{
public static void main(String[] args)
{
String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}
use this to replace the last character
lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));
suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code
String lletres = "BBB";
int atIndex = lletres.lastIndexOf('B');
char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
lletres= lletres.substring(0, atIndex)+ReplacementChar;
System.out.println(lletres);
output
BBC

Spliting and reading from string in Java

I've written a code that works similar to calculator, but it solves cryptarithmetic equations. It works fine with basic operations like +-*/.
Now I added the power and root operation and it doesn't work when I use those two new operations. It seems that the problem is with the way I split the input string. The problem is that it doesn't split the string with "^" operator. Here is the code where the problem occurs:
private void findOperator() {
// TODO Auto-generated method stub
String[] tempString = this.rawInputString.split("");
for(String s : tempString){
if(s.equals("+")){
this.operator = "[+]";
break;
}
else if(s.equals("*")){
this.operator = "[*]";
break;
}
else if(s.equals("-")){
this.operator = s;
break;
}
else if(s.equals("/")){
this.operator = s;
break;
}
else if(s.equals("^")){
this.operator = s;
break;
}
else if(s.equals("sqrt")){
this.operator = s;
break;
}
}
}
public void parseInput(){
String[] tempString = rawInputString.split(this.operator);
this.firstString = tempString[0].split("");
this.firstLetterFirstNumber = this.firstString[0];
String temporarySecondPart = tempString[1];//This is where it says I
//have the problem, but it works fine
//with other operators
this.operator = rawInputString.substring(this.firstString.length,this.firstString.length+1);
tempString = temporarySecondPart.split("=");
this.secondString = tempString[0].split("");
this.firstLetterSecondNUmber = this.secondString[0];
this.result = tempString[1].split("");
this.firstLetterResult = this.result[0];
}
split is using regular expression (regex) as argument. Some characters have special meaning in regex (we call them metacharacters) and ^ is one of them. It usually represent start of string, or can be used to create negative character set like [^a-z] will represent any character which is not in range a and z.
If you want to change ^ into simple literal you need to escape it like
split("\\^")
but safer way would be allowing regex to do escaping for you. To do so use
split(Pattern.quote("^"))
or in your case
split(Pattern.quote(operator)).
You are doing some weird jumping through hoops in that code.
findOperator() splits rawInputString into 1-character strings, then searches for the first +, *, -, /, or ^ (ignoring the non-working sqrt) and assigns it to this.operator as a regex.
You then split rawInputString using that regex. Why?
You just found it in findOperator(), so you know exactly where it is.
Then you begin splitting, and splitting, and splitting...
All that, when all you want to do is parse a string a op b = c?
And you seem to want to save it all in fields:
firstString a as a String[] of 1-character
operator op
secondString b as a String[] of 1-character
result c as a String[] of 1-character
firstLetterFirstNumber First 1-character string in firstString
firstLetterSecondNUmber First 1-character string in secondString
firstLetterResult First 1-character string in result
And no error handling whatsoever, so you get ArrayIndexOutOfBoundsException, instead of some meaningful error.
Just use one regular expression, and all your values are ready for you.
And using toCharArray() will give you the 1-character values as a char[].
String rawInputString = "3√343=7";
String regex = "(.+?)([-+*/^√])(.+?)=(.+)";
Matcher m = Pattern.compile(regex).matcher(rawInputString);
if (! m.matches())
throw new IllegalArgumentException("Bad input: " + rawInputString);
char[] firstString = m.group(1).toCharArray();
String operator = m.group(2);
char[] secondString = m.group(3).toCharArray();
char[] result = m.group(4).toCharArray();
char firstLetterFirstNumber = firstString[0];
char firstLetterSecondNUmber = secondString[0];
char firstLetterResult = result[0];
System.out.println("firstString = " + Arrays.toString(firstString));
System.out.println("operator = " + operator);
System.out.println("secondString = " + Arrays.toString(secondString));
System.out.println("result = " + Arrays.toString(result));
OUTPUT
firstString = [3]
operator = √
secondString = [3, 4, 3]
result = [7]
try this regex out
String abc = "a+b-c*d^f";
String reg = "((?<=[<=|>=|==|\\+|\\*|\\-|<|>|/|=|\\^])|(?=[<=|>=|==|\\+|\\*|\\-|<|>|/|=|\\^]))";
String [] arr = abc.split(reg); //split your String according to Expression
for(String obj : arr)
System.out.println(obj);
Your Output will be like that
a
+
b
-
c
*
d
^
f
Note :- Your Complete Mathematical expression will be split into an array of String just by finding any mathematical expression in row

Character swapping

I'm trying to swap the first and last character in a string so what I did was I was able to retrieve its first and last characters but am now having hard times putting them all together:
String name="pera";
char[] c = name.toCharArray();
char first = c[0];
char last = c[c.length-1];
name.replace(first, last);
name.replace(last, first);
System.out.println(name);
Although I am getting for the variable 'first' the value of "p" and for the variable 'last' the value of "a", these methods replace() are not turning up with a valid result as the name stays as it is. Does anyone have any idea on how to finish this?
1) String are immutable in Java. so name.replace(first, last) will not modify name but will return a new String.
2) String#replace(char oldChar, char newChar) replaces all occurrences of oldChar in this string with newChar.
For example:
System.out.println("aaaddd".replace("a","d"));
Will give :
dddddd
Possible solution : If you convert your String to a char[], you can easily swap the characters :
public static String inverseFirstAndLast(String str){
char[] c = str.toCharArray();
Character temp = c[0];
c[0] = c[c.length-1];
c[c.length-1]=temp;
return new String(c);
}
Swapping the first with the last is easy like this:
String str = "SwapDemo";
String swapped = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);
The method you tried will replace all the occurrences of the passed argument, which is not what you want. The code above will do what you want.
As Arnoud pointed out, strings are immutable. But, fixing that issue, you will still get wrong results for:
acbbc
for example
c[0] = last;
c[c.length-1] = first;
System.out.println(new String(c));
Here's a regex based solution:
String str = "demo";
String swapped = str.replaceAll("^(.)(.*)(.)$", "$3$2$1");
Related to solution of #Martijn Courteaux. You can also store the result inside same str String hence saving a little bit of space, like this:
String str = "pera";
String str = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);

Java Converting binary sequence to char

I looked for this about an hour now, but couldn't get any advise specific to my problem. What I'd like to do is take a string of 0's and 1's and manipulate a char that it fits the given String pattern. For example:
char c = 'b'
String s = "00000000 01100001";
Now I'd like to manipulate the bits in c, so that they match the bit pattern specified in s. As result c would be printed as 'a' (if I'm not completely wrong about it). Any help appreciated!
You can do
char a = (char) Integer.parseInt("0000000001100001", 2);
To do the conversion from binary string to Integer, use parseInt with the 2nd argument as 2.
int temp = Integer.parseInt("01100001", 2);
You can modify with binary operators (&,|,^), but if what you really want is to just assign a variable, you can do it with casts.
char c = 'c';
System.out.println((char)(c&temp));
System.out.println((char)temp);
How about:
String s = "00000000 01100001";
String[] w = s.split(" ");
char c = (char)(Integer.parseInt(w[0], 2) * 256 + Integer.parseInt(w[1], 2));
This allows for the leading zeroes of each byte to be omitted. If you know they're there, you can just replace the space out of the string and use a single parseInt() call:
char c = (char)Integer.parseInt(s.replace(" ", ""), 2);

How can I split two digit into two different strings?

I have month in, which contains a value such as 12. I am trying to split it into two different strings e.g. a=1 and b=2. How do I do this?
There are several ways to do this.
// Working with Strings ------
String str = "12";
// Get char array
char[] chars = str.toCharArray();
// Two substrings
String firstStr = str.substring(0,1);
String secondStr = str.substring(1,2);
// Working with ints ---------
int i = 12;
int firstInt = i / 10; // Divide
int secondInt = i % 10; // Modulo
Use String.charAt(index) method to return a character and use Character.toString(char) to convert it to String.
Simplest way might be to convert it to a String and then use charAt() to read the characters one by one.
Sounds like a homework question :)
String x = "12";
String[] x_arr= x.split("");
your chars will be located in
x[1]
x[2]
and eventually you can go on with the index if you passed a longer string (like a year).
Just avoid x[0] because it is an empty string.
String splits[] = "12".split("#?") would work.
Use :
str.split("\\w.+")
For Example :
String[] parts = "12".split("\\w.+");
String a = parts[0]
Strign b = parts[1]
You can Take a look here
http://www.roseindia.net/regularexpressions/splitting-string.shtml
Try this:
String input = "12";
System.out.println(input.charAt(0)); // gives '1'
System.out.println(input.charAt(1)); // gives '2'
Furthermore, if you wish to have '1' and '2' as Strings (not as chars), you can do this :
String firstDigit = input.charAt(0) + "";
String secondDigit = input.charAt(1) + "";
Good luck !
Konstantin
EDIT: Lets assume that 'month' is variable of type java.util.Date. Then:
String monthToString = new SimpleDateFormat("MM").format(month);
String firstDigit = monthToString.charAt(0) + "";
String secondDigit = monthToString.charAt(1) + "";
You can use the method substring of class String.
There is the documentation: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#substring(int, int)
The algorithm is not complex ;)

Categories

Resources