How to ignore white spaces in Java [duplicate] - java

This question already has answers here:
Remove all occurrences of char from string
(13 answers)
Closed 5 years ago.
I was wondering how to ignore spaces in Java. This program allows you to enter your first, middle and surname which then outputs your initials. I'm now trying to make it ignore any white spaces. Thanks in advance!
String fullName;
char firstName;
char secondName;
char surname;
int space1;
int space2;
System.out.println("Please enter your first name, your second name and your surname: ");
fullName = kybd.nextLine();
firstName = fullName.charAt(0);
space1 = fullName.indexOf(" ");
secondName = fullName.charAt(space1 + 1);
space2 = fullName.lastIndexOf(" ");
surname = fullName.charAt(space2 + 1);
System.out.println("Initials: " + firstName + secondName + surname);

Explanation
You can implicitly ignore them by just removing them from your input text.
Therefore replace all occurrences with "" (empty text):
fullName = fullName.replaceAll(" ", "");
After that call fullName won't contain a whitespace anymore.
However you'll then get a problem with your logic as you split on whitespaces.
Solution
An alternative could be to first trim the text (removing leading and trailing whitespaces). Then do your split and after that you can remove all other whitespaces:
fullName = kybd.nextLine();
// Remove leading and trailing whitespaces
fullName = fullName.trim();
// Bounds
firstSpace = fullName.indexOf(" ");
lastSpace = fullName.lastIndexOf(" ");
// Extract names
String fullFirstName = fullName.substring(0, firstSpace);
String fullSecondName = fullName.substring(firstSpace + 1, lastSpace);
String fullSurname = fullName.substring(lastSpace + 1);
// Trim everything
fullFirstName = fullFirstName.trim(); // Not needed
fullSecondName = fullSecondName.trim();
fullSurname = fullSurname.trim();
// Get initials
firstName = fullFirstName.charAt(0);
secondName = fullSecondName.charAt(0);
surname = fullSurname.charAt(0);
Example
Let's take a look at an example input (_ stands for whitespace):
__John___Richard_Doe_____
We will first trim fullName and thus get:
John___Richard_Doe
Now we identify the first and the last whitespace and split on them:
First name: John
Second name: ___Richard
Surname: _Doe
Last we also trim everything and get:
First name: John
Second name: Richard
Surname: Doe
With charAt(0) we access the initials:
First name: J
Second name: R
Surname: D
More dynamic
Another more dynamic approach would be to merge all successive whitespaces into a single whitespace. Therefore you would need to traverse the text from left to right and start recording once you see a whitespace, end recording if visiting a non-whitespace character, then replace that section by a single whitespace.
Our example then is:
_John_Richard_Doe_
And after an additional trim you can use your regular approach again:
John_Richard_Doe
Or you can use split(" ") and then reject every empty String:
Iterator<String> elements = Pattern.compile(" ").splitAsStream(fullName)
.filter(e -> !e.isEmpty()) // Reject empty elements
.collect(Collectors.toList()) // Collect to list
.iterator() // Iterator
firstName = elements.next().charAt(0);
secondName = elements.next().charAt(0);
surname = elements.next().charAt(0);
Using the example again the Stream first consists of
"", "", "John", "", "", "Richard", "Doe", "", "", "", "", ""
after the filtering it's
"John", "Richard", "Doe"
Minus Sign
As you said you also want
Richard Jack Smith-Adams
output RJS-A, you can simply split on - after splitting on the whitespace.
Pattern spacePatt = Pattern.compile(" ");
Pattern minusPatt = Pattern.compile("-");
String result = spacePatt.splitAsStream(fullName) // Split on " "
.filter(e -> !e.isEmpty()) // Reject empty elements
.map(minusPatt::splitAsStream) // Split on "-"
.map(stream ->
stream.map(e -> e.substring(0, 1))) // Get initials
.map(stream ->
stream.collect(Collectors.joining("-"))) // Add "-"
.collect(Collectors.joining("")); // Concatenate
Which outputs RJS-A.
This approach is a bit more complicated as we need to maintain the information of the sub-streams, we can't just flatMap everything together, otherwise we wouldn't know where to add the - again. So in the middle part we are indeed operating on Stream<Stream<String>> objects.

I think what you're after here is the split method in String
Which you could use like this:
String fullName = "John Alexander Macdonald";
String[] split = fullName.split(" "); // ["John", "Alexander", "Macdonald"]
The other thing you might want is the trim method which removes spaces from the front and the back of a string.
String withSpaces = " a b c ";
String trimmed = withSpace.trim(); // "a b c"

Related

Java - String splitting

I read a txt with data in the following format: Name Address Hobbies
Example(Bob Smith ABC Street Swimming)
and Assigned it into String z
Then I used z.split to separate each field using " " as the delimiter(space) but it separated Bob Smith into two different strings while it should be as one field, same with the address. Is there a method I can use to get it in the particular format I want?
P.S Apologies if I explained it vaguely, English isn't my first language.
String z;
try {
BufferedReader br = new BufferedReader(new FileReader("desc.txt"));
z = br.readLine();
} catch(IOException io) {
io.printStackTrace();
}
String[] temp = z.split(" ");
If the format of name and address parts is fixed to consist of two parts, you could just join them:
String z = ""; // z must be initialized
// use try-with-resources to ensure the reader is closed properly
try (BufferedReader br = new BufferedReader(new FileReader("desc.txt"))) {
z = br.readLine();
} catch(IOException io) {
io.printStackTrace();
}
String[] temp = z.split(" ");
String name = String.join(" ", temp[0], temp[1]);
String address = String.join(" ", temp[2], temp[3]);
String hobby = temp[4];
Another option could be to create a format string as a regular expression and use it to parse the input line using named groups (?<group_name>capturing text):
// use named groups to define parts of the line
Pattern format = Pattern.compile("(?<name>\\w+\\s\\w+)\\s(?<address>\\w+\\s\\w+)\\s(?<hobby>\\w+)");
Matcher match = format.matcher(z);
if (match.matches()) {
String name = match.group("name");
String address = match.group("address");
String hobby = match.group("hobby");
System.out.printf("Input line matched: name=%s address=%s hobby=%s%n", name, address, hobby);
} else {
System.out.println("Input line not matching: " + z);
}
I can think of three solutions.
In order from best to worst:
Different delimiter
Enforce the format to always have two names, two address parts and one hobby
Have a dictionary with names and hobbies, check each word to determine which type it is and then group them together as needed.
(The 3rd option is not meant as a serious alternative.)
As others have mentioned, using spaces as both field delimiter and inside fields is problematic. You could use a regex pattern to split the line (paste (\w+ \w+) (\w+ \w+) (.+) in Regex101 for an explanation):
Pattern pattern = Pattern.compile("(\\w+ \\w+) (\\w+ \\w+) (.+)");
Matcher matcher = pattern.matcher("Bob Smith ABC Street Bowling Fishing Rollerblading");
System.out.println("matcher.matches() = " + matcher.matches());
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println("matcher.group(" + i + ") = " + matcher.group(i));
}
This would give the following output:
matcher.matches() = true
matcher.group(0) = Bob Smith ABC Street Bowling Fishing Rollerblading
matcher.group(1) = Bob Smith
matcher.group(2) = ABC Street
matcher.group(3) = Bowling Fishing Rollerblading
However this only works for this exact format. If you get a line with three name parts for example:
John B Smith ABC Street Swimming
This will get split into John B as the name, Smith ABC as the address and Street Swimming as hobbies.
So either make 100% sure your input will always match this format or use a different delimiter.
The split() method majorly works on the 2 things:
Delimiter and
The String Object
Sometimes on limit too.
Whatever limit you will provide, the split() method will do its work according to that.
It doesn't understand whether the left substring is a name or not, same as for the right substring.
Have a look at this code snippet:
String assets = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = assets.split(":");
System.out.println("splits.size: " + splits.length);
for(String asset: splits){
System.out.println(assets);
}
OutPut
splits.size: 5
Gold
Stocks
Fixed Income // with space
Commodity
Interest Rates // with space
The output came with spaces because I provided the ; as a delimiter.
This probably helped you to get your answer.
Find Detailed Information on Split():
Top 5 Use cases of Split()
Java Docs : Split()
It depends on the data you're dealing with. Will the name always consist of a first and last name? Then you can simply combine the first two elements from the resulting array into a new string.
Otherwise, you might have to find a different way to separate out the different pieces within the txt file. Possibly a comma? Some character that you know won't ever be used in your normal data.
Assuming that every line follows the format
Bob Smith ABC Street Swimming
ie, name surname.... this code can manually manipulate the data for you:
String[] temp = z.split(" ");
String[] temp2 = new String[temp.length - 1];
temp2[0] = temp[0] + " " + temp[1];
for (int i = 2; i < temp.length; i++) {
temp2[i] = temp2[i];
}
temp = temp2;

String index out of range on space bar character

For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);

Extract text from string and write to another string

I have string like this: "Welcome Vitalii Mckay "
I need to cut from this string my name and surname, it should left in new string: "Mckay, Vitalii".
But it should be good not just for my name, it should works for other names with different length, for example:
"Welcome John Smith " -> "Smith, John"
or
"Welcome Andrea J. " -> "J., Andrea".
String name = "Welcome Vitalii Mckay";
String[] parts = name.split("\\ ");
name = parts[2] + ", " + parts[1];
Based on #Vishal's answer and OP's comment on #Max's answer, I believe this will work:
String name = " Welcome Vitalii Mckay "; // with spaces in the beginning and in the end
String[] parts = name.trim().split(" "); // you don't really need the \\
name = parts[2] + ", " + parts[1];
Just make sure you trim your String input.
Could you just use a delimiter?
i.e. use a delimiter to separate the three strings, and only print out the two needed values (Surname [2]/Firstname [1])
String s = "Welcome Vitalii Mckay";
String[] split = s.split("\\s+");
System.out.println(split[2] + ", " + split[1]);
// "Welcome"
// followed by the not of space one or more times
// then a space
// followed by anything one or more times
Pattern pattern = Pattern.compile("Welcome ([^ ]+) (.+)");
Matcher matcher = pattern.matcher("Welcome Vitalii Mckay");
if (!matcher.matches()) throw new Exception();
String firstName = matcher.group(1); // groups are captured between ()
String lastName = matcher.group(2); // groups are captured between ()

How to include white spaces in next() without using nextLine() in Java

I am trying to make the user input a string, which can both contain spaces or not. So in that, I'm using NextLine();
However, i'm trying to search a text file with that string, therefore i'm using next() to store each string it goes through with the scanner, I tried using NextLine() but it would take the whole line, I just need the words before a comma.
so far here's my code
System.out.print("Cool, now give me your Airport Name: ");
String AirportName = kb.nextLine();
AirportName = AirportName + ",";
while (myFile.hasNextLine()) {
ATA = myFile.next();
city = myFile.next();
country = myFile.next();
myFile.nextLine();
// System.out.println(city);
if (city.equalsIgnoreCase(AirportName)) {
result++;
System.out.println("The IATA code for "+AirportName.substring(0, AirportName.length()-1) + " is: " +ATA.substring(0, ATA.length()-1));
break;
}
}
The code works when the user inputs a word with no spaces, but when they input two words, the condition isn't met.
the text file just includes a number of Airports, their IATA, city, and country. Here's a sample:
ADL, Adelaide, Australia
IXE, Mangalore, India
BOM, Mumbai, India
PPP, Proserpine Queensland, Australia
By default, next() searches for first whitespace as a delimiter. You can change this behaviour like this:
Scanner s = new Scanner(input);
s.useDelimiter("\\s*,\\s*");
By this, s.next() will match commas as delimiters for your input (preceeded or followed by zero or more whitespaces)
Check out the String#split method.
Here's an example:
String test = "ADL, Adelaide, Australia\n"
+ "IXE, Mangalore, India\n"
+ "BOM, Mumbai, India\n"
+ "PPP, Proserpine Queensland, Australia\n";
Scanner scan = new Scanner(test);
String strings[] = null;
while(scan.hasNextLine()) {
// ",\\s" matches one comma followed by one white space ", "
strings = scan.nextLine().split(",\\s");
for(String tmp: strings) {
System.out.println(tmp);
}
}
Output:
ADL
Adelaide
Australia
IXE
Mangalore
India
BOM
Mumbai
India
PPP
Proserpine Queensland
Australia

How to remove spaces in between the String

I have below String
string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
string = str.replace("\\s","").trim();
which returning
str = "Book Your Domain And Get Online Today."
But what is want is
str = "Book Your Domain And Get Online Today."
I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance
Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.
string = str.replaceAll("\\s+"," ")
You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:
string = str.replaceAll("\\s{2,}"," ");
It will replace 2 or more consecutive whitespaces with a single whitespace.
First get rid of multiple spaces:
String after = before.trim().replaceAll(" +", " ");
If you want to just remove the white space between 2 words or characters and not at the end of string
then here is the
regex that i have used,
String s = " N OR 15 2 ";
Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(s);
while(m.find()){
String replacestr = "";
int i = m.start();
while(i<m.end()){
replacestr = replacestr + s.charAt(i);
i++;
}
m = pattern.matcher(s);
}
System.out.println(s);
it will only remove the space between characters or words not spaces at the ends
and the output is
NOR152
Eg. to remove space between words in a string:
String example = "Interactive Resource";
System.out.println("Without space string: "+ example.replaceAll("\\s",""));
Output:
Without space string: InteractiveResource
If you want to print a String without space, just add the argument sep='' to the print function, since this argument's default value is " ".
//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234
a.replaceAll("\\s", "")
String s2=" 1 2 3 4 5 ";
String after=s2.replace(" ", "");
this work for me
String string_a = "AAAA BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);
OUTPUT will be:AAA BBB

Categories

Resources