Formatting user Input with specific char at specific point in java - java

*Edit 2,"undeclared variable" The following is the example that my textbook provides. I may have used incorrect terms in saying undeclared variable.
String fName = "Harry";
String lName = "Morgan";
String name = fName + lName;
results in the string "HarryMorgan"
What if you’d like the first and last name separated by a space? No problem:
String name = fName + " " + lName;
This statement concatenates three strings:
fName, the string literal " ", and lName.
The result is"Harry Morgan"
The citation provided is a guideline. Please check each citation for accuracy before use.
*Edit, Question is: How do I insert characters into an undeclared string?
Example:
Input: X839WS21R4E877
Display: X-839 WS21 R4-E87 (7)
Input: x83rws21b3e87a
Display: X-83R WS21 B3-E87 (A)
I am taking a 14 character input from the user. I need to format in spaces and " - " into the input. Also all of the letters need to be capitalized, although I have that already taken care of.
The following code is what I have.
System.out.println("Please enter your 14 character code.");
String name = input.nextLine();
if (name.length()>14) {//code thanks to namlik from stackoverflow
String cutName = name.substring(0, 14).toUpperCase();
name = cutName;
}
System.out.print(name);
Here is another post I found I feel might work but I don't understand how to implement it into my code or if it would work. Basic way to insert character into string.
The following link is to another similar question. Python vs of Question
This link is what came up when I tried to do a search however I am not using int to string so I don't believe it is relevant. Example of search results
I believe my scenario would benefit others to be able to insert other types of characters into an unknown string. I realize that using / you can insert special characters. However everything I have found so far uses the assumption that you are using a declared variable.
I believe I need to insert the characters I desire spaces and " - " at set points using the .substring(x, x) method however I am unsure how to go about doing so with out messing up my limit of only 14 characters.
Thank you in advance for your help.

If i understand your input output example correctly then the best way is to use regex groups and String::replaceAll like this :
String[] strings = {"X839WS21R4E877", "x83rws21b3e87a"};
for(String str : strings){
str = str.toUpperCase();// to convert the string to UpperCase
str = str.replaceAll("([A-Z0-9])([A-Z0-9]{3})([A-Z0-9]{4})([A-Z0-9]{2})([A-Z0-9]{3})([A-Z0-9])",
"$1-$2 $3 $4-$5 ($6)");
System.out.println(str);
}
Outputs
X-839 WS21 R4-E87 (7)
X-83R WS21 B3-E87 (A)
regex demo
details
([A-Z0-9])([A-Z0-9]{3})([A-Z0-9]{4})([A-Z0-9]{2})([A-Z0-9]{3})([A-Z0-9])
You have to devide your inputs to groups in the previouse regew there are 6 groups :
([A-Z0-9]) groupe 1 matches first letter or numbers
([A-Z0-9]{3}) groupe 3 matches 3 letters or numbers
([A-Z0-9]{4}) groupe 4 matches 4 letters or numbers
([A-Z0-9]{2}) groupe 2 matches 2 letters or numbers
([A-Z0-9]{3}) groupe 3 matches 3 letters or numbers
([A-Z0-9]) groupe 6 matches last character

Related

Search for a general sub-string within a string in Java [duplicate]

This question already has answers here:
How to get substrings from strings [duplicate]
(4 answers)
Closed 4 years ago.
I am new to Java. I want to ask how to search for a general sub-string within a given string.
For example:-
In the string 12345.67 I want to search for the sub-string .67
And in the string 1.00 I want to search for the string .00.
I basically want to search for the string after the radical (.), provided the number of characters after radical are only 2.
According to my knowledge search for general sub-string is not possible, I thereby asked for your help.
I wish to print the input (stored in the database) , a floating point number, into Indian Currency format, i.e, comma separated.
I even looked at various previous posts but none of them seemed to help me as almost everyone of them failed to produce the requite output for decimal point
According to my knowledge search for general sub-string is not possible
So you may learn a bit more, here String substring(int beginIndex) method :
String str = "12345.67";
String res = str.substring(str.indexOf('.')); // .67
If you want to check that there is only 2 digits after . :
String str = "12345.67";
String res = str.substring(str.indexOf('.') + 1); // 67
if(res.length() == 2)
System.out.println("Good, 2 digits");
else
System.out.println("Holy sh** there isn't 2 digits);
You can use split plus the substring to achieve your objective
String test = "12345.67";
System.out.println(test.split("\\.")[1].substring(0,2));
In the split function, you can pass the regex with which you could give the separator and in a substring function with the number of characters you want to extract
Next to the answer provided from #azro you may also use regex:
String string = "12345.67";
Pattern ppattern = Pattern.compile("\\d+(\\.\\d{2})");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String sub = matcher.group(1);
System.out.println(sub);
}
Which prints:
.67
String str = "12345.67";
String searchString = "." + str.split("\\.")[1];
if(str.contains(searchString)){
System.out.println("The String contains the subString");
}
else{
System.out.println("The String doesn't contains the subString");
}

How to use 'matches()' method to see if string matches format

I'm currently working on something where the code inputs about thousands of lines of strings. Each line must follow a specific format like the following:
"Name,#,#,#,#,#,#"
Where 'name' is the name of a movie (we can assume the name won't have any numbers), and # is any number from 0-10. Each value MUST be separated by a comma.
My code is the following:
if (line.matches(".*[a-zA-z].*,([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10)")) {
System.out.println("no");
}
else {
System.out.println(line);
The issue is that the title of the film can't have commas in it. If it does, it needs to be printed. However, my 'matches()' doesn't seem to pick up lines that have a comma in the title. It seems to me that my code specifically outlines that if the next entry (separated by a comma) is not an integer, then it does not match, and therefore the 'line' needs to be printed.
Can anyone see where I'm going wrong in this?
You are saying that rules are:
Lines must be 7 comma-separated values: a name and 6 numbers in range 0-10.
The name must not contain a comma.
We can assume the name won't have any numbers, but it is not a requirement that it cannot.
Since the only invalid character in a name is a comma, so regex would be:
[^,]*,(?:[0-9]|10),(?:[0-9]|10),(?:[0-9]|10),(?:[0-9]|10),(?:[0-9]|10),(?:[0-9]|10)
If you want to capture the fields, you would use this code:
Pattern p = Pattern.compile("([^,]*),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10)");
for (String line : lines) {
Matcher m = p.matcher(line);
if (! m.matches()) {
System.out.println("Invalid line: " + line);
} else {
System.out.println("Name: " + m.group(1));
System.out.println(" Values: " + m.group(2)
+ " " + m.group(3)
+ " " + m.group(4)
+ " " + m.group(5)
+ " " + m.group(6)
+ " " + m.group(7));
}
}
Test
String[] lines = { "Buffalo Bill and the Indians, or Sitting Bull's History Lesson,0,1,2,3,4,5",
"Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb,6,7,8,9,10,0",
"300,1,2,3,4,5,6"};
Output
Invalid line: Buffalo Bill and the Indians, or Sitting Bull's History Lesson,0,1,2,3,4,5
Name: Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb
Values: 6 7 8 9 10 0
Name: 300
Values: 1 2 3 4 5 6
First movie name has a comma, so it doesn't match.
Second movie name has special characters (. and :), but no comma, so it matches.
Third movie name is "300", which is an actual movie, so it matches.
The problem lies within with the .*. This part is able to include the comma.
Fri,dayaervsere,6,4,78,7
<--><--------->^
.* [a-zA-Z] ,( [...]
So, basically you only need to get rid of the .*. Instead, apply a quantifier to your first group:
[a-zA-Z]* // to match any number of characters
or
[a-zA-Z]+ // to match at least one character
If you do use regex to solve this, I'd recommend allowing commas in the 'Name' part of your regex. Focus on making sure there are 6 numbers, each following a comma. You can check to see if the name fits an appropriate criteria later.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
// before your for-loop, create a pattern (Assuming no digits in title)
Pattern p = Pattern.compile("([^0-9]+),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10)");
// ...
// later on in your actual for-loop for each line.
Matcher m = p.matcher(line);
if (m.matches())
{
String title = m.group(1);
// do extra checking for the title if needed
}
else
{
// print no
}
The following regex supposed to solve your problem:
^([a-zA-Z ]+),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10),([0-9]|10)
Or the shorter version of it, with no code duplication:
^([a-zA-Z ]+)(,([0-9]|10)){6}
Testing
"The Killer,6,7,3,6,8,1" matches the pattern.
"The Kill,er,6,7,3,6,8,1" doesn't match the pattern, as you wanted.
Also, spaces in the title are supported.
You can play with it here.

Java - Regular Expressions Split on character after and before certain words

I'm having trouble figuring out how to grab a certain part of a string using regular expressions in JAVA. Here's my input string:
application.APPLICATION NAME.123456789.status
I need to grab the portion of the string called "APPLICATION NAME". I can't simply split on the period character becuase APPLICATION NAME may itself include a period. The first word, "application", will always remain the same and the characters after "APPLICATION NAME" will always be numbers.
I've been able to split on period and grab the 1st index but as I mentioned, APPLICATION NAME may itself include periods so this is no good. I've also been able to grab the first and second to last index of a period but that seems ineffecient and would like to future-proof by using REGEX.
I've googled around for hours and haven't been able to find much guidance. Thanks!
You can use ^application\.(.*)\.\d with find(), or application\.(.*)\.\d.* with matches().
Sample code using find():
private static void test(String input) {
String regex = "^application\\.(.*)\\.\\d";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find())
System.out.println(input + ": Found \"" + m.group(1) + "\"");
else
System.out.println(input + ": **NOT FOUND**");
}
public static void main(String[] args) {
test("application.APPLICATION NAME.123456789.status");
test("application.Other.App.Name.123456789.status");
test("application.App 55 name.123456789.status");
test("application.App.55.name.123456789.status");
test("bad input");
}
Output
application.APPLICATION NAME.123456789.status: Found "APPLICATION NAME"
application.Other.App.Name.123456789.status: Found "Other.App.Name"
application.App 55 name.123456789.status: Found "App 55 name"
application.App.55.name.123456789.status: Found "App.55.name"
bad input: **NOT FOUND**
The above will work as long as "status" doesn't start with a digit.
With split(), you could save key.split("\\.") in a String[] s and, in a second time, join from s[1] to s[s.length-3].
With regexes you can do:
String appName = key.replaceAll("application\\.(.*)\\.\\d+\\.\\w+")", "$1");
Why split? Just:
String appName = input.replaceAll(".*?\\.(.*)\\.\\d+\\..*", "$1");
This also correctly handles a dot then digits within the application name, but only works correctly if you know the input is in the expected format.
To handle "bad" input by returning blank if the pattern is not matched, be more strict and use an optional that will always match (replace) the entire input:
String appName = input.replaceAll("^application\\.(.*)\\.\\d+\\.\\w+$|.*", "$1");

How to get initial of last name in java using regex

Input : "Chris Gayle"
Required output : "Chris G"
I am currently using :
String inputStr = "Chris Gayle";
String[] strArr = inputStr.split(" ");
String output =strArr[0] + " " + strArr[1].charAt(0);
However, I was hoping to find an implementation that takes up fewer lines of code by using the 'replaceAll' function in the String class by using pattern matching techniques.
I wouldn't actually use regex for this.
Example
String input = "Chris Gayle";
System.out.println(input.substring(0, input.lastIndexOf(" ") + 2));
Output
Chris G
The advantage here is that you can have names with multiple items, i.e.... "Chris Foo Gayle" --> "Chris Foo G".
Note
This implies each item is separated by space, or at least the last name is. It would return unexpected results with something like "Chris J.Gayle".
Even worse, if your input does not contain any space (i.e. single name).
If that is a possible case, you should check that input.lastIndexOf(" ") != -1 prior to invoking substring.
Through replaceAll function.
string.replaceAll("(?<=\\s.).*", "");
The above regex would match all the characters which are preceded by a space and a single character.
One line answer:
System.out.println("Chris Gayle".replaceAll("([a-z]*)$", ""));
Note: last name must start with capital letter.

How to delete duplicated characters in a string?

Okay, I'm a huge newbie in the world of java and I can't seem to get this program right. I am suppose to delete the duplicated characters in a 2 worded string and printing the non duplicated characters.
for example:I input the words "computer program." the output should be "cute" because these are the only char's that are not repeated.
I made it until here:
public static void main(String[] args) {
System.out.print("Input two words: ");
String str1 = Keyboard.readString();
String words[] = str1.split(" ");
String str2 = words[0] + " ";
String str3 = words[words.length - 1] ;
}
but i don't know how to output the characters. Could someone help me?
I don't know if I should use if, switch, for, do, or do-while...... I'm confused.
what you need is to build up logic for your problem. First break the problem statement and start finding solution for that. Here you go for steps,
Read every character from a string.
Add it to a collection, but before adding that, just check whether it exists.
If it exists just remove it and continue the reading of characteer.
Once you are done with reading the characters, just print the contents of collection to console using System.out.println.
I will recommend you to refer books like "Think like A Programmer". This will help you to get started with logic building.
Just a hint: use a hash map (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html).
Adding following code after last line of your main program will resolve your issue.
char[] strChars = str2.toCharArray();
String newStr="";
for (char c : strChars) {
String charStr = ""+c;
if(!str3.contains(charStr.toLowerCase()) && !str3.contains(charStr.toUpperCase())){
newStr+=c;
}
}
System.out.println(newStr);
This code loops through all the characters of the first word and check if the second string contains that character (In any form of case Lower or Upper). If it is not containing, adding it to output string and at the end printing it.
Hope this will work in your case.
How about doing it in just 1 line?
str = str.replaceAll("(.)(?=.*\\1)", "");

Categories

Resources