Arrays.toString() prints String with [] and , ---any alternative? - java

while programming i accepted a string ...changed it to char array using
string.toCharArray()
...and had to change it back to string (because i am using recurion and have to pass the string as argument each time)..how to do this..???
i tried using array.toString()...but it passes gibberis..beginning with #....then i searched here and found out about Arrays.toString().....but learned that it does indeed convert it to string but adds [] and , ...i need the original string....how to go about this...heres part of the code..
public String replace(String str, char ch) {
if(count ==0){
Scanner sc2= new Scanner(System.in);
System.out.println("enter the character to be replaced with ");
c2 =sc2.next().charAt(0);
len=str.length();
}
arr=str.toCharArray();
if(arr[count]==ch){
arr[count]=c2;
}
count++;
str=Arrays.toString(arr); // Problem
if(count<len)
temp=replace(str,ch);
else
temp=str;
return temp;
}

Try this
String chString = new String(myCharArray);

If you want to convert a char[] to a String, then just use new String(array).

You can pass this array to String constructor:
String original = new String(arr);

Related

Why to add a Empty String while adding an string with int?

In the below when I wasn't adding the ""(Empty String), the output was in int, which is pretty abnormal because adding a String with an int always gives a string. But as soon as I added the Empty String thing, the code seemed to work fine. In both the cases,I was adding a string from the string array that I created earlier in the code.
import java.io.*;
public class TooLong{
public static void main(String[] args) throws IOException{
InputStreamReader n = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(n);
byte i ;
i=Byte.parseByte(input.readLine());
String origWords[] = new String[i];
for (int j=0;j<i;j++) origWords[j]= input.readLine();
for (int j=0;j<i;j++){
int charLength = origWords[j].length();
if (charLength < 11) System.out.println(origWords[j]);
else System.out.println(origWords[j].charAt(0) +""+ (charLength-2) + origWords[j].charAt(charLength-1) );
}
}
}
I assume, you are trying to achieve “internationalization ⇒ i18n”
That is because String.charAt(int) returns char. Which will be treated as numerical when using +.
By using + with the empty String you force the compiler to convert everything to String
You can use String.substring(0,1) instead of the first charAt to force type String conversion
The charAt() method of String returns the char. char is one of the primitive data types. char is a textual primitive, however, it also can do arithmetic operations like numerical primitives. The codes below are examples for it:
`public static void main(String args[]){
String st = "i am a string";
char c = st.charAt(0);
System.out.println(c);
System.out.println(c+ st.charAt(2));
System.out.println(c+ "" + st.charAt(2));
}
`
The result of the above code will be:
i
202
ia
Hope this example makes it clear.

locate specific char and replace it in Java

I am getting around a hundred url strings from my JSON. Example:
media.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_189765_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_162_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_532535677_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_1612452_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_10976562**_b.jpg**
As you see, the only common thing in these urls is the end "b.jpg"
How can I replace the character b with other character?
I have tried with this method:
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
Here is when I call it:
hs.thumbNailUrl = changeCharInPosition(65, 'l',hs.thumbNailUrl);
But the position of b always changes, so this method is inefficient.
If you are always only going to have one char of that value you can just use .replace() to replace that character.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace('b', 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
Now if you are trying to replace based off of the index of the character you could use StringBuilder and find the location of b by using substring and finding the location of b by subtracting the the number of chars after b from the total length.
public static void main(String args[]) {
StringBuilder x = new StringBuilder("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x.setCharAt(x.length() - 7, 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
EDIT
Third option:
Here we are replacing the char at the last index of 'b'.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace(x.charAt(x.lastIndexOf('b')), 'y');
System.out.println(x);
}
Now obviously you can loop through and use a new character for each string.
Change your call to changeCharInPosition from
hs.thumbNailUrl = changeCharInPosition(65, 'l', hs.thumbNailUrl);
to
hs.thumbNailUrl = changeCharInPosition(hs.thumbNailUrl.indexOf("b.jpg"),
'l', hs.thumbNailUrl);
You can use String.lastIndexOf(String) in order to find the last occurrence of one String inside another.
e.g.
private String replace(String url, String thumnailUri){
String toReplace = "**b.jpg**";
int lastBIndex = url.lastIndexOf(toReplace);
return url.substring(0, lastBIndex) + thumnailUri;
}
You could also use String.replace(String, String) e.g.
url.replace("**b.jpg**", hs.thumnailUri);

Java Using a stack to reverse the words in a sentence [duplicate]

This question already has answers here:
Reversing characters in each word in a sentence - Stack Implementation
(6 answers)
Closed 9 years ago.
I am supposed to write a code that reads a sentence from the user and prints the characters of the words in the sentence backwards. It should include a helper method that takes a String as a parameter and returns a new String with the characters reversed. The individual words are reversed, for example the sentence "Hi dog cat". would print "iH god tac". I can make the entire sentence reverse but i cant figure out how to reverse individual words. Thanks! Also, i know how to return the String once i have found it, but i just cant get the right string
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.println("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
String k = PrintStack(sentence);
}
private static String PrintStack(String sentence)
{
String reverse;
String stringReversed = "";
Stack<String> stack= new Stack<String>();
sentence.split(" ");
for(int i=0;i<sentence.length(); i++)
{
stack.push(sentence.substring(i, i+1));
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}
I will type an expatiation so you can still get the experience of writing the code, rather than me just giving you the code.
First create a Stack of Characters. Then use add each character in the String to the Stack, starting with the first char, then the second, and so on. Now either clear the String or create a new String to store the reversed word. Finally, add each character from the Stack to the String. This will pull the last character off first, then the second to last, and so on.
Note: I believe you have to use the Character wrapper class, rather than the primitive char; I may be incorrect about that though.
If you aren't familiar with how Stacks work, here is a nice interactive tool to visualize it: http://www.cise.ufl.edu/~sahni/dsaaj/JavaVersions/Stacks/AbstractStack/AbstractStack.htm
Change:
Stack<String> stack = new Stack<String>();
to be
Stack<Character> stack = new Stack<Character>();
and refactor your methods code as necessary; i.e.
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I did it with a different kind of stack, but I suspect this might help
private static String reverseWord(String in) {
if (in.length() < 2) {
return in;
}
return reverseWord(in.substring(1)) + in.substring(0, 1);
}
private static String reverseSentence(String in) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
if (sb.length() > 0)
sb.append(' ');
sb.append(reverseWord(st.nextToken()));
}
return sb.toString();
}
public static void main(String[] args) {
String sentence = "Hi dog cat";
String expectedOutput = "iH god tac";
System.out.println(expectedOutput
.equals(reverseSentence(sentence)));
}
Outputs
true

Split a string in Java and picking up a part of it

Say I got a string from a text file like
"Yes ABC 123
Yes DEF 456
Yes GHI 789"
I use this code to split the string by whitespace.
while (inputFile.hasNext())
{
String stuff = inputFile.nextLine();
String[] tokens = stuff.split(" ");
for (String s : tokens)
System.out.println(s);
}
But I also want to assign Yes to a boolean, ABC to another string, 123 to a int.
How can I pick them up separately? Thank you!
boolean b=tokens[0].equalsIgnoreCase("yes");
String name=tokens[1];
int i=Integer.parseInt(tokens[2]);
Could you clarify what the exact purpose of what you're doing is? You can refer to the separate Strings with tokens[i] with i being the index. You could throw these into a switch statement (since Java 7) and match for the words you're looking for. Then you can take further action, i.e. convert the Strings to Booleans or Ints.
You should consider checking the input to be valid too even if you are expecting the file to always have those 3 words separated by a space.
Create Class Line and List<Line> that will store all your file into list:
public class Line{
private boolean mFlag = false;
private int mNum = 0;
private String mStr;
public Line(String stuff) {
String[] tokens = stuff.split("[ ]+");
if(tokens.length ==3){
mFlag=tokens[0].equalsIgnoreCase("yes");
mNum=Integer.parseInt(tokens[1]);
mStr=tokens[3];
}
}
}
and call it:
public static void main(String[] args) {
List<Line> list = new ArrayList<Line>();
Line line;
while (inputFile.hasNext())
{
String stuff = inputFile.nextLine();
line = new Line(stuff);
list.add(line);
}
}
If your input String is going to be in the same format always i.e. boolean,String ,int then you can access the individual indices of token array and convert them to your specified format
boolean opinion = tokens[0].equalsIgnoreCase("yes");
String temp = token[1];
int i = Integer.parseInt(token[2])
But you might require to create an array or something that stores the values for consecutive inputs that user does otherwise these variables would be over ridden for every new input from user.

How to divide string to single chars and put them in the array?

I realise it's pretty basic.
I need to ask user for an string input. Then I divide string to single char array and print it in a console. I have to ignore spaces
Tried this but when I input "this is test string" as output I get only {t h i s}
String tekst;
Scanner odczyt = new Scanner(System.in);
System.out.println("Wpisz tekst");
tekst = odczyt.next();
int iloscZnakow = tekst.length();
char tablica[] = new char[iloscZnakow];
tablica = tekst.toCharArray();
System.out.println(Arrays.toString(tablica));
You can use toCharArray() method of String class.
Please replace odczyt.next(); with odczyt.nextLine();

Categories

Resources