Formatting a string using Java - java

I have string which goes like this-
abc/def/ghi/jkl/mno/pqr
Now I want to represent this as-
abc/
def/
ghi/
jkl/
mno/
pqr
I am trying to achieve this using JAVA, can any one please provide me a sample code.

Try with:
String input = "abc/def/ghi/jkl/mno/pqr";
String[] output = input.split("/");
for (int i = 0; i < output.length; i++) {
output[i] += "/";
}

One approach would be to replace each occurrence of "/" with "/\n" (\n is a new line character.)
String provides a replace() method for doing this.

I'll hint you. Have a look at the java docs for String class and find a method for replacing / with /\n in the string.

You can use the following code
String strValue="abc/def/ghi/jkl/mno/pqr";
String strValue1=strValue;
System.out.println("Actual Value \n >>>"+strValue);
strValue1=strValue1.replaceAll("/","/\n");
System.out.println("\nstrFormattedValue >>>\n"+strValue1);
The output of the program is as follows:-
Actual Value
>>>abc/def/ghi/jkl/mno/pqr
strFormattedValue >>>
abc/
def/
ghi/
jkl/
mno/
pqr
Press any key to continue . . .

Related

Reading only 1 char then using method from String in java

In my task I need to read this input 1,2,3. I read it from file.
String listOfNumbers= reader.readLine();
listOfNumbers= listOfNumbers.replace(",", " ");
for (int i = 0; i< listOfNumbers.length(); i++) {
if (Character.isDigit(listOfNumbers.charAt(i)))
System.out.println(listOfNumbers);
}
Output is always 1 2 3 but I want for every number to send it to function.
E.g.
if (listOfNumbers) =1 then send it to function.
if (listOfNumbers) = 2 ....
I mean if listOfNumber equals some number.
My friend did it with regex but I didn't find right solutio.
you can split the String like so:
val members = listOfNumbers.split(",")
And then you have each individual number separately in the List members and you can pass them as parameters to whatever function you want.
Try to use an array of string with the method Split() is easier to work with

Is it possible to replace parts of strings with variables?

I was just wondering if there was a way to replace strings with variables. Specifically through the methods replaceAll("", ""). Wondering if its possible to do something like :
int i = 2;
replaceAll("\\D", i);
If not, is there a roundabout way to do this?
You can only replace parts of Strings with a String.
String text = "Hello World";
int i = 2;
text = text.replaceAll("o", ""+i);
String#replaceAll(x,x) only accepts a String as its second parameter. The solution here is to convert your int into a String:
myString.replaceAll("\\D", String.valueOf(i));
use this:
int i = 2;
replaceAll("\\D", ""+i);
yes it is. As you assume you can use
s = s.replaceAll("textToReplace",Integer.toString(i));
to replace all the occurrences of textToReplace in the String s.

Replace char at specific substring

first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);

Java assign matches to variable

I am trying to do something like this but I doesnt seem to work
String test = input.matches("[^a-zA-Z\\s]");
I get an error saying incompatible types
Is there any way fixing this or any other methods?
EDIT
This is what I'm trying to achieve
Lets say i have this string
String full = " This i$ an aaasdAr yeEeeAs oofo qwdsgy XY9 ";
and i need to have the output as $9
this works but its a bit too messy
for (int index = 0; index <= input.length() - 1; index ++)
{
if(String.valueOf(input.charAt(index)).matches("[^a-zA-Z\\s]"))
{
System.out.print(String.valueOf(input.charAt(index)));
}
}
The method matches returns a boolean. As you are trying to assign that to a String instead, you're getting the compilation error.
To solve your specific problem, you can use String.replaceAll, which takes a replacement regex:
String input = " This i$ an aaasdAr yeEeeAs oofo qwdsgy XY9 ";
String output = input.replaceAll("[a-zA-Z\\s]", "");
System.out.println(output);
This replaces everything that matches the regex with the empty string, and it prints $9.

How to search the whole string for a specific word?

I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?
You have three way to search if an string contain substring or not:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:
b = string.indexOf("I am") >= 0;
Check out the contains(CharSequence) method
Try this-
etsearch.getText().toString().contains((String) countryCode[i]);
You could use contains. As in:
myString.contains("xxx");
See also: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html, specifically the contains area.
Use the following:
public boolean contains (CharSequence cs)
Since: API Level 1
Determines if this String contains the sequence of characters in the CharSequence passed.
Parameters
cs the character sequence to search for.
Returns
true if the sequence of characters are contained in this string, otherwise false
Actually, the default Arrayadapter class in android only seems to search from the beginning of whole words but by using the custom Arrayadapter class, you can search for parts of the arbitrary string. I have created the whole custom class and released the library. It is very easy to use. You can check the implementation and usage from here or by clicking on the link provided below.
https://github.com/mohitjha727/Advanced-Search-Filter
You can refer to this simple example-
We have names " Mohit " and "Rohan" and if We put " M" only then Mohit shows up in search result, but when we put "oh" then both Mohit and Rohan show up as they have the common letter 'oh'.
Thank You.

Categories