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 ;)
Related
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
Assume the below string :
String value = "161207CAD140000,0";
how can i get the index of the first char and the index of the last char for the substring CAD
notice that the size of the substring may be changed from 2 ,3 or etc chars i want the solution to be dynamic.
You can use String.indexOf(String str) function which will return starting indexof the "CAD". Then add one less then the length of String to find in the returned value, that will be your last character index of "CAD".
Something like this:
String value = "161207CAD140000,0";
String str = "CAD";
String datePart = value.substring(0, value.indexOf(str)); // for finding the date part
String amountStr = value.substring(value.indexOf(str) + str.length()); //for finding the amount part
System.out.println(datePart +" "+amountStr);`
Now suppose the String "CAD" is dynamic and you don't know what value it will have, in that case its better to use regex. Please see below code snippet:
String value = "161207CAD140000,0";
String patt = "[\\d,]+";
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(value);
while(matcher.find()){
System.out.println(matcher.group());
}
If any question let me know in comments. Hope it helps.
This would do the job for any string.
String value = "161207CAD140000,0";
String searchedString = "CAD"
int firstIndex = value.indexOf(searchedString);
int lastCharIndex = firstIndex + searchedString.length();
There are methods in the String class for such requirements. You can use the indexOf and lastIndexOf methods to get the positions. e.g
int index = value.indexOf("C"); //This returns 6
int lastIndex = value.lastIndexOf("D"); //this returns 8
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]);
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);
I know of no easy way to do this. Suppose I have the following string-
"abcdefgh"
I want to get a string by replacing the third character 'c' with 'x'.
The long way out is this -
s1 = substring before third character = "ab" in this case
s2 = new character = "x" in this case
s3 = substring after third character = "defgh" in this case
finalString = s1 + s2 + s3
Is there a simpler way? There should be some function like
public String replace(int pos, char replacement)
Use StringBuilder#replace().
StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();
http://ideone.com/Tg5ut
You can convert the String to a char[] and then replace the character. Then convert the char[] back to a String.
String s = "asdf";
char[] arr = s.toCharArray();
arr[0] = 'b';
s = new String(arr);
No. There is no simpler way than to concatenate the pieces.
Try using a StringBuilder instead StringBuilder Java Page
Since every String is basically just a char[] anyway, you could just grab it and manipulate the individual chars that way.
Try the String.replace(Char oldChar, Char newChar) method or use a StringBuilder
How about:
String crap = "crap";
String replaced = crap.replace(crap.charAt(index), newchar);
but this will replace all instances of that character
String yourString = "abcdef"
String newString = yourString.replaceAll("c" , "x");
System.out.println("This is the replaced String: " + newString);
This is the replaced String: abxdef