How to increment a particular character in string (Java) - java

suppose i have a string s1 = "abcd";
output should be s1 = "abca";
I want to decrement/increment the last character in the string so that it matches the first character of the string .
Since String doesn't allow to modify the data
How can I achieve this.

Since, as you noted, String is immutable you will have to perform an assignment. I'd do a substring() and then concatenate the first letter. Something like
String s1 = "abcd";
s1 = s1.substring(0, s1.length() - 1) + s1.charAt(0);
System.out.println(s1);
Output is (as requested)
abca
JLS-4.2.1. Integral Types and Values does document that char is an integral type. That allows you to do something like
public static String modifyCharInString(String in, int index, int ammount) {
if (in == null || in.isEmpty() || index < 0 || index >= in.length()) {
return in;
}
StringBuilder sb = new StringBuilder(in);
sb.setCharAt(index, (char) (in.charAt(index) + ammount));
return sb.toString();
}
And then you an call it like
public static void main(String[] args) {
String s1 = "abcd";
s1 = modifyCharInString(s1, s1.length() - 1, -3);
System.out.println(s1);
}
Output is (again)
abca

For editing Strings you can use StringBuilder class. This allows you to get better performance, than using substring().
String oldString = "abcd";
StringBuilder sb = new StringBuilder(oldString);
sb.setCharAt(sb.length() - 1, sb.charAt(0));
String newString = sb.toString();

Related

Merge 2 strings by printing the characters from each String one after the other

This is an interview which was asked recently.
Suppose there are 2 strings.
String a="test";
String b="lambda";
Reverse the String.
//tset
//adbmal
Expected output should be : tasdebtmal
Here we are trying to print characters from each string.
"t" from 1st String is printed, followed by "a" from other string, and so on.
So, "tasdebtm" is printed from each string and the remaining characters "al" is appended at the end.
int endA = a.length() - 1;
int endB = b.length() - 1;
StringBuilder str = new StringBuilder();
//add values to str till both the strings are not covered
while(endA>-1 && endB>-1){
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
add all chars of a if any is remaining
while(endA>-1){
str.append(a.charAt(endA--));
}
add all chars of b if any is remaining
while(endB>-1){
str.append(b.charAt(endB--));
}
System.out.println(str);
Definitely, there are other ways to do this too.
public class CharsinString2 {
public static void main(String[] args) {
String a="abra"; //arba
String b="kadabra";//arbadak // aarrbbaadak
int endA=a.length()-1;
int endB=b.length()-1;
StringBuilder str=new StringBuilder();
while(endA>-1 && endB>-1) {
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
while(endA>-1) {
str.append(a.charAt(endA--));
}
while(endB>-1) {
str.append(b.charAt(endB--));
}
System.out.println(str);
}
}

Failed to parse a String to int

I don't know what's wrong with parsing the String to an int part in my code. Before the parsing, everything looks correct.
import java.io.IOException;
public class TheWindow {
public static void main(String[] args) throws IOException{
String s = "13.16";
double d = Double.parseDouble(s);
System.out.println(d);
char[] ch = s.toCharArray();
char[] ch2 = new char[s.length()];
for(int i = 0; i < ch.length; i++){
if(ch[i] == '.'){
break;
}else{
ch2[i] = ch[i];
}
}
String s2 = new String(ch2);
System.out.println(s2);
try{
s2.trim();
int newI = Integer.parseInt(s2);
System.out.println(newI);
}catch(Exception e){
System.out.println("Failed");
}
}
}
You are not storing the returned String from trim() anywhere. You could either do:
s2 = s2.trim();
int newI = Integer.parseInt(s2);
or
int newI = Integer.parseInt(s2.trim());
The problem with your code is that you are breaking out of the for loop when the '.' character is reached.
Since you created ch2 with a length of 5 then this means the last three spaces are null. When you put that in a string with String s2 = new String(ch2) then then three special characters are added at the end of the string, one for each empty space in the ch2 character array.
To fix this then set the length of the ch2 array to be two, or if you want to dynamically determine the length, do the index of the '' in theString swiths.indexOf('.')and then set the length of the array to one minus the index of ''.
This should fix your problem as stated in your question.
s2 = s2.trim();
change this part of code in the try block.
You are trimming the string but not assigning it to the variable that refers it due to which the spaces are still left out and parsing such string is throwing an exception.
Java objects are immutable, meaning they can't be changed, and Strings are Objects in Java.
Your line s2.trim() will return the trimmed version, but s2 will not be directly modified. However, you aren't storing it anywhere, so when you parse it on the next line, it will be with the untrimmed s2.
What you want is s2 = s2.trim(), which will store the trimmed version back in.
From what I understand, you want to truncate the decimal. If so, then you can just find the decimal place and substring the string, then parse it.
Note: You might want to add back in some try-catches for strings that still cannot be parsed.
private static int tryParseInt(String str) {
int decimalIndex = str.indexOf(".");
if (decimalIndex != -1) {
return Integer.parseInt(str.substring(0, decimalIndex));
} else {
return Integer.parseInt(str);
}
}
public static void main(String[] args) {
System.out.println(tryParseInt("13.16")); // 13
}
You have uninitialized characters in your ch2 array. You can set them to space before trimming or use a different string constructor. For example:
public static void main(String[] args) {
String s = "13.16";
double d = Double.parseDouble(s);
System.out.println(d);
char[] ch = s.toCharArray();
char[] ch2 = new char[s.length()];
int i = 0;
for(i = 0; i < ch.length; i++){
if(ch[i] == '.'){
break;
}else{
ch2[i] = ch[i];
}
}
String s2 = new String(ch2, 0, i);
System.out.println(s2);
try{
s2.trim();
int newI = Integer.parseInt(s2);
System.out.println(newI);
}catch(Exception e){
System.out.println("Failed");
}
}
}

Java concat with integer and string

I want to write a program that would pass an integer and a string to a value-returning method. I know how to do this part, however I need to concatenate the int (which is 2) and the string (which says "bye"), and have it print the string the number of the int. (Example: Bye Bye).
I will respond clarifying the issue as soon as possible.
You can concatenate String with int in Java like this:
String result = "some " + 2;
The string should go first in this "+" operator.
Try this.
static String repeat(int times, String s) {
return IntStream.range(0, times)
.mapToObj(x -> s)
.collect(Collectors.joining(" "));
}
and
System.out.println(repeat(2, "bye"));
// -> bye bye
public String repeatString(String str, int n)
{
if(n<1 || str==null)
return str;
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++)
{
sb.append(str);
if(i!=(n-1)) // If not the last word then add space
sb.append(" ");
}
return sb.toString();
}
try this out
private String repeateAndConcateString (int prm_Repeat, String prm_wordToRepeat){
if(prm_Repeat <=0 || prm_wordToRepeat == null){
return "";
}
String temp = "";
for(int i= 1 ; i<=prm_Repeat ; i++){ // loop through the number of times to concatinate.
temp += prm_wordToRepeat; //Concate the String Repeatly 1 to prm_Repeat
}
return temp; // this will return Concatinate String.
}
For string repeat, Apache StringUtils have method repeat.
Or an implementation without externals:
public static String repeat(int n, String s){
StringBuilder sb = new StringBuilder(n * s.length());
while(n--)
sb.append(s);
return sb.toString();
}
Integers can be converted to a string by both references: String.valueOf and Integer.toString. String concatenation works like math addition (+).

string printing reference in java

I have this code where I am printing a string variable. The first output is showing what is expected but the second time it prints some unreadable output(I think its reference id). Please explain: Why does this happen?
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return c.toString();
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
}
}
Output:
boy
[C#60aeb0
the frontToBack() method is calling toString() on a character array object char[] which is why you see the [C#60aebo. Instead of calling toString() return with new String(c); or String.valueOf(c)
Array types in Java do not override Object#toString(). In other words, array types inherit Object's implementation of toString() which is just
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
which is the output you see
[C#60aeb0
If you want to see a representation of the contents of an array, use Arrays.toString(..).
In your case, you seem to want to switch the first and last characters and return the corresponding string. In that case, just create a new String instance by passing the char[] to the constructor.
You don't need to implement a custom class to do this. The functionality is already in java.
This question has already been answered # Reverse a string in Java
(duplicate thread)
use new String(c) to c.toString();
c.toString() c mean array of chars toString() print hash method
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return new String(c);
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
} }

Implode/explode a string: what escaping scheme would you suggest?

Suppose I have two strings to "join" with a delimiter.
String s1 = "aaa", s2 = "bbb"; // input strings
String s3 = s1 + "-" + s2; // join the strings with dash
I can use s3.split("-") to get s1 and s2. Now, what if s1 or s2 contains dashes? Suppose also that s1 and s2 may contain any ASCII printable and I don't want to use non-printable characters as a delimiter.
What kind of escaping would you suggest in this case?
If I could define the format, delimiters, etc. I would use OpenCSV and use it's defaults.
You could use an uncommon character sequence, such as ;:; as a delimiter instead of a single character.
Here is another working solution, that doesn't use a separator, but that joins the lengths of the strings at the end of the imploded string to be able to re-explode it after:
public static void main(String[] args) throws Exception {
String imploded = implode("me", "and", "mrs.", "jones");
System.out.println(imploded);
String[] exploded = explode(imploded);
System.out.println(Arrays.asList(exploded));
}
public static String implode(String... strings) {
StringBuilder concat = new StringBuilder();
StringBuilder lengths = new StringBuilder();
int i = 0;
for (String string : strings) {
concat.append(string);
if (i > 0) {
lengths.append("|");
}
lengths.append(string.length());
i++;
}
return concat.toString() + "#" + lengths.toString();
}
public static String[] explode(String string) {
int last = string.lastIndexOf("#");
String toExplode = string.substring(0, last);
String[] lengths = string.substring(last + 1).split("\\|");
String[] strings = new String[lengths.length];
int i = 0;
for (String length : lengths) {
int l = Integer.valueOf(length);
strings[i] = toExplode.substring(0, l);
toExplode = toExplode.substring(l);
i++;
}
return strings;
}
Prints:
meandmrs.jones#2|3|4|5
[me, and, mrs., jones]
Why don't you just store those strings in an array and join them with dash each time you want to display them to user?

Categories