Just a quick question, as after an hour of research I haven't yet found a solution to my problem:
I have a given String (from online DB) that may contain spaces and I need to break the line at every space.
The output must be a String
Could someone help please?
Cheers
String newString = oldString.replaceAll(" ","\n");
You can do it like this for e.g.
String s = I am a dragon.
s.replaceAll(" ", "\n");
You can split It
class A{
public static void main(String[] args) {
String word = "Hello Hello Hello Hello ";// Now Your String like This
String arr[] = word.split(" ");// You can Split it from every Space
for (String name : arr) {
System.out.println(name);// output is a String
}
}
}
Related
Im trying to figure out how i can remove certain characters in an email address before the domain name using nothing but a simple regex and replaceAll in Java.
In email addresses,
Need to remove any number of . before #<domain name>
Also remove anything between + up to # but not including #. For instance in joebloggs+123#domain.com should be joebloggs#domain.com.
So far I have,
class Main {
public static void main(String[] args) {
String matchingRegex = "(\\.|(\\+.*(?=#)))";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
}
}
which replaces everything including the domain name.
joebloggs#gmailcom
What i really need is joebloggs#gmail.com.
Can this be achieved with regex alone ?
Another look ahead did the trick in the end.
class Main {
public static void main(String[] args) {
String matchingRegex = "((\\.+)(?=.*#)|(\\+.*(?=#)))";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joebloggs+123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123+456#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joebloggs#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123+456.789#gmail.com".replaceAll(matchingRegex, ""));
}
}
Results in,
joebloggs#gmail.com
joebloggs#gmail.com
joebloggs#gmail.com
joebloggs123#gmail.com
joebloggs123#gmail.com
joebloggs#gmail.com
joebloggs123#gmail.com
You could try spliting the string (the email) on the # and running replaceAll on the the first half and then put the strings back together.
Check out: How to split a string in Java
For splitting strings.
Try this regex [.](?=.*#)|(?=\\+)(.*)(?=#). It looks up dots up to # (even if there's text in between), or everything from + up to #. Hope it helps https://regex101.com/r/gyUpta/1
class Main {
public static void main(String[] args) {
String matchingRegex = "[.](?=.*#)|(?=\\+)(.*)(?=#)";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
}
}
This will do the trick...
public static void main(String args[]) {
String matchingRegex = "(\\.|(\\+.*(?=#)))";
String email = "joe.bloggs+123#gmail.com";
String user = email.substring(0, email.indexOf("#")+1);
String domain = email.substring(email.indexOf("#")+1);
System.out.println(user.replaceAll(matchingRegex, "") + domain);
}
This is the easiest way I have found to do it.
String address = "joe.bloggs+123#gmail.com";
int at = address.indexOf("#");
address = address.substring(0, at).replaceAll("\\.|\\+.*", "")
+ address.substring(at);
System.out.println(address);
if you try to split for regex sorry i don't remember java this example is in javascript
let string = "joe.bloggs+123#gmail.com"
//firts the function
function splitString(params) {
return params.split(/\+(.)+\#/)
}
//second the concat
let list = splitString(string)
// the first element+the las element
console.log(`${list[0]}${list[list.length -1]}`)
I have a date 07/December/2020, and I want to print JUST the last letter of December, R, before the slash. I am going to then combine this last letter with the first letter of December by concatenating them so it says 'DR'. This is a lot easier in theory...
class Main {
public static void main(String[] args) {
String dateCod = "07/December/2020";
String firstletterLastletter= (dateCod.substring(3,4) + dateCod.substring(9));
}
}
System.out.println(firstletterLastletter);
}
}
I tried this, but it won't work. I also tried paring it with substring and lastIndexOf combined, but that wouldn't work. I feel like I have no idea what I am doing, and feebly trying to understand how to do something by throwing darts in the dark...
How can I print just the last letter before the second slash?
Use split() to get the middle part of the String and then use charAt() method to get character at specific index.
String dateCod = "07/December/2020";
String middle = dateCod.split("/")[1];
String res = middle.charAt(0) + "" + middle.charAt(middle.length() - 1);
If you want to later print it as DR use toUppercase() method on res
You can use replaceAll with regex
String result = dateCod.replaceAll(".*/(.)[^/]+(.)/[^/]*", "$1$2");// Output Dr
regex demo
You can still get what you want with substring(), but the key is splitting the date string into tokens first. Splitting allows you to avoid dealing with the different quantity of characters in each month name.
public class Test
{
public static void main(String[] args)
{
String s = "07/December/2020";
String[] tokens = s.split("/");
String month = tokens[1];
String firstLetter = month.substring(0, 1);
String lastLetter = month.substring(month.length() - 1);
System.out.println(firstLetter + lastLetter);
}
}
I have the following code,
String s = " Hello I'm a multi spaced String"
In string s, there are multiple (indeterminate) spaces; but, I need to print it as %temp%Hello I'm a%temp%multi spaced String
How can I do this?
Use regex \s{2,} and replaceAll() method like this:
s.replaceAll("\\s{2,}","%temp%");
Output
%temp%Hello I'm a%temp%multi spaced String
Code
public class HelloWorld
{
public static void main(String[] args)
{
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s{2,}","%temp%");
System.out.println(s);
}
}
You can use a regular expression like \s\s+ which matches a white space followed by one or more additional whitespaces. Something like,
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s\\s+", "%temp%");
System.out.println(s);
Outputs (as requested)
%temp%Hello I'm a%temp%multi spaced String
import java.util.*;
import java.io.*;
public class OptimusPrime{
public static void main(String[] args){
System.out.println("Please enter the sentence");
Scanner scan= new Scanner(System.in);
String bucky=scan.nextLine();
int pOs=bucky.indexOf("is");
System.out.println(pOs);
if(pOs==-1){
System.out.println("the statement is invalid for the question");
}
else{
String nay=bucky.replace("is", "was");
System.out.println(nay);
}
}
}
Now I know the "replace" method is wrong as i want to change the particular string "is" and not the portion of other string elements. I also tried using SetChar method but I guess the "string is immutable" concept applies here.
How to go about it?
Using String.replaceAll() instead enables you to use a regex. You can use the predefined character class \W in order to catch a non-word character :
System.out.println("This is not difficult".replaceAll("\\Wis", ""));
Output :
This not difficult
The verb is disappeared but not the isfrom This.
Note 1 : It also removes the non-word character. If you want to keep it, you can capture it with some parenthesis in the regex then reintroduce it with $1:
System.out.println("This [is not difficult".replaceAll("(\\W)is", "$1"));
Output :
This [ not difficult
Note 2 : If you want to handle a string which begins with is, this line will not be enough but it is quite easy to handle with another regex.
System.out.println("is not difficult".replaceAll("^is", ""));
Output :
not difficult
If you use replaceAll instead, then you can use \b to use the word boundary to perform a "whole words only" search.
See this example:
public static void main(final String... args) {
System.out.println(replace("this is great", "is", "was"));
System.out.println(replace("crysis", "is", "was"));
System.out.println(replace("island", "is", "was"));
System.out.println(replace("is it great?", "is", "was"));
}
private static String replace(final String source, final String replace, final String with) {
return source.replaceAll("\\b" + replace + "\\b", with);
}
The output is:
this was great
crysis
island
was it great?
Simpler way:
String nay = bucky.replaceAll(" is ", " was ");
Match word boundary:
String nay = bucky.replaceAll("\\bis\\b", "was");
to replace string with another string you can use this
if Your string variable contains like this
bucky ="Android is my friend";
Then you can do like this
bucky =bucky.replace("is","are");
and your bucky's data will be like this Android are my friend
Hope this helps you.
How to split a sentence into two parts in JAVA? If there is the following
String sentence = "I love Java <=> I love Python"
How can I return I love Java and I love Python thus separately ignoring <=>?
public void changeSentence(String line)
{
String[] words = line.split(" ");
for(int i = 0; i < words.length; i++)
{
if(!(words[i].equals("<=>")))
{
}
}
}
It can be done using the method given below of class String
METHOD: (public String[] split(String regex, int limit)
Regex: The String/Character you wish to remove & split remaining text
Limit: How many String that should be returned
public class TestSplit
{
public static void main(String args[])
{
String str = new String("I Love Java <=> I Love Python");
for (String retval: str.split("<=> ",2))
{
System.out.println(retval);
}
}
}
Output:
I Love Java
I Love Python
There are some other facts I am aware about are listed below
If you won't specify limit by 'keeping it blank'/'specify 0' then the compiler will split string every time '<=>' is found
e.g.
public class TestSplit
{
public static void main(String args[])
{
String str = new String("I Love Java <=> I Love Python <=> I Love Stackoverflow");
for (String retval: str.split("<=> "))
{
System.out.println(retval);
}
}
}
Output:
I Love Java
I Love Python
I Love Stackoverflow
Why not do:
String[] words = line.split("<=>");
for(String word : words){
System.out.println(word);
}
Output:
I love Java
I love Python
public String[] changeSentence(String line){
String[] substrings = line.split("<=>");
return substrings;
}
You can also split with StringTokenizer.
The code for splitting the strings based upon delimiter is below:
StringTokenizer stringTokenizer = new StringTokenizer(sentence,"<=>");
while(stringTokenizer.hasMoreTokens()) {
System.out.println(stringTokenizer.nextToken());
}
I hope this helps
Thanks
How can I return I love Java and I love Python thus separately ignoring <=>?
First of all as you have said that you want your method to return separate words
(Strings technically), for that you need change your return type from void to String[ ]
Second, you are using
String[] words = line.split(" ");
this will split the String where spaces appear which would yield you array of Strings containing
I
love
Java
<=>
I
love
Python
as different words stored as separate Strings in your words array.
so what you should do is
Strings[] words=line.split("<=>");
and return words
Full code should be like this
public String[] changeSentence(String line)
{
String[] words = line.split("<=>");
return words;
}