I have two types of Strings. One is "abcdEfgh" and "abcd efgh". That means first String is having upper case letter in between and second string is having white space. So now how do I check these two pattern string in java and make two strings.
String givenString;
if (givenString.equals("abcdEfgh")) {
String str1 = abcd;
String str2 = Efgh;
} else (givenString.equals("abcd efgh") {
String str1 = abcd;
String str2 = efgh;
}
Please provide the solution
Thanks
You can split using regex \\s|(?=[A-Z])
\\s is to deal with case of whitespace.
(?=[A-Z])is positive lookahead. It finds capital letter but keeps the delimiter while splitting.
.
String givenString;
String split[] = givenString.split("\\s|(?=[A-Z])");
String str1 = split[0];
String str2 = split[1];
for both cases
Test case 1
//case 1
givenString = "abcdEfgh";
str1 = abcd
str2 = Efgh
Test case 2
//case 2
givenString = "abcd efgh";
str1 = abcd
str2 = efgh
You need to combine the two conditions using the OR operator |. You've already figured out split by space is simply " ". The uppercase example is answered by Java: Split string when an uppercase letter is found
Example
String one = "abcdEfgh";
String two = "abcd efgh";
System.out.println(Arrays.toString(one.split(" |(?=\\p{Upper})")));
System.out.println(Arrays.toString(two.split(" |(?=\\p{Upper})")));
Output
[abcd, Efgh]
[abcd, efgh]
Keep it simple, search for space in givenString instead of case sensitive matchs
if(givenString.indexOf(" ") != -1){
System.out.println( "The string has spaces");
}else{
System.out.println( "The string has NO spaces");
}
Related
String 1:
func1(test1)
String 2:
func1(test2)
I want to compare these 2 strings upto the first open braces '('.
So for the given example it should return true since the string upto '(' in both the strings is 'func1'.
Is there any way to do that without splitting?
String#substring() method will help on this case this combined with String#indexOf() method
String x1 = "func1(test1)";
String x2 = "func1(test1)";
String methName1 = x1.substring(0, x1.indexOf("("));
String methName2 = x2.substring(0, x2.indexOf("("));
System.out.println(methName1);
System.out.println(methName2);
System.out.println(methName1.equals(methName2));
You can use String.matches() method to test if the second string matches the splitted one from the first string:
String s1 = "func1(test1)";
String s2 = "func1(test2)";
String methName = s1.substring(0, s1.indexOf("("));
System.out.println(s2.matches(methName+ "(.*)"));
This is a working Demo.
Alternatively you can compare the strings directly by replacing everything after '(' by empty string.
String str1 = "func1(test1)";
String str2 = "func1(test2)";
System.out.println(str1.replaceAll("\\(.*", "").equals(str2.replaceAll("\\(.*", "")));
You can use regex to find every thing between any delimiters, in your case () and compare the results, for example :
String START_DEL = "\\("; //the start delimiter
String END_DEL = "\\)"; //the end delimiter
String str1 = "func1(test1)";
String str2 = "func1(test2)";
Pattern p = Pattern.compile(START_DEL + "(.*?)" + END_DEL);//This mean "\\((.*?)\\)"
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
if (m1.find() && m2.find()) {
System.out.println(m1.group(1).equals(m2.group(1)));
}
Let's say the user inputs "hello 0 1" into a string. How can I separate this string into a string that says "hello" followed by two separate ints 0 and 1? I've tried using the substring method with the parameters (0,userInput.nextInt()) and this doesn't work.
You can achieve it this way:
String teststring = "hello 0 1";
String[] splitstr = teststring.split(" ");
String firstString = splitstr[0];
int firstNo = Integer.valueOf(splitstr[1]);
int secondNo = Integer.valueOf(splitstr[2]);
There are multiple ways in which you can extract numbers. Split string or use tokenizer to create token like:
String str = "Hello 10 11";
StringTokenizer tokenizer = new StringTokenizer(str);
String token;
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if (token.matches("\\d+" )) {//if its a number
System.out.println("Number is " + token);
}
}
You are doing substring by reading a number from system input which you could automate but would be tedious.
If you String contains Spaces , then Splitting it using space as delimeter is an option
String []splittedString=inputString.split(" ");//Splitting on basis of space
Alternatively you can use Regular expression
public static void findWordFollowedByInt()
{
String inputString="Hello 1 2";
Pattern p=Pattern.compile("\\w+");
Matcher matcher=p.matcher(hello);
while(matcher.find())
{
System.out.println(matcher.group());
}
}
Output :
Hello
1
2
Split along the spaces as others have said. Then use something like the Apache commons Lang, which has numberutils that can check if a string is a number. If it is, you can then do something like Double.parseDouble(str).
Consider an example,
String str1 = "hello world";
String str2 = str1.replace("low","xxx");
System.out.println(str2);
Now when I print str2, it should print helxxxorld.
My requirement is that I don't want to first remove all spaces in str1 and then replace. How can I do this?
You can use the String#replaceAll() method, which allows you to pass a regex:
String str1 = "hello world";
String str2 = str1.replaceAll("l\\s*o\\s*w","xxx");
System.out.println(str2);
\\s* will match zero or more spaces after the l and o signs
Use a regular expression with whitespace:
String str2 = str1.replaceAll("l\\s*o\\s*w", "xxx");
Output:
helxxxorld
Title seems to be simple. But I don't get a good Idea. This is the situation
I have String like this in my Java program
String scz="3282E81WHT-22/24";
I want to split the above string into 3 Strings, such that
first string value should be 3282e81,
Next string should be WHT(ie, the String part of above string and this part is Always of 3 Characters ),
Next String value should be 22/24 (Which will always occur after -)
In short
String first= /* do some expression on scz And value should be "3282e81" */;
String second= /* do some expression on scz And value should be "WHT" */;
String third= /* do some expression on scz And value should be "22/24" */;
Input can also be like
scz="324P25BLK-12";
So 324P25 will be first String, BLK will be second (of 3 Characters). 12 will be third ( After - symbol )
How to solve this?
You can use a regex like this (\d+[A-Z]\d+)([A-Z]+)-([/\d]+) and using Matcher.group(int) method you can get your string splitted into three groups.
Code snippet
String str = "3282E81WHT-22/24";
//str = "324P25BLK-12";
Pattern pattern = Pattern.compile("(\\d+[A-Z]\\d+)([A-Z]+)-([/\\d]+)");
Matcher match = pattern.matcher(str);
System.out.println(match.matches());
System.out.println(match.group(1));
System.out.println(match.group(2));
System.out.println(match.group(3));
Output
true
3282E81
WHT
22/24
Use this to split the entire string in to two
String[] parts = issueField.split("-");
String first = parts[0];
String second= parts[1];
Use this to split the first string into two
if (first!=null && first.length()>=3){
String lastThree=first.substring(first.length()-3);
}
if your String's Second part (WHT) etc will always be of 3 Characters then following code will surely help you
String scz = "3282E81WHT-22/24";
String Third[] = scz.split("-");
String rev = new StringBuilder(Third[0]).reverse().toString();
String Second=rev.substring(0,3);
String First=rev.substring(3,rev.length());
// here Reverse your String Back to Original
First=new StringBuilder(First).reverse().toString();
Second=new StringBuilder(Second).reverse().toString();
System.out.println(First + " " + Second + " " + Third[1]);
You can use subString() method to get this goals.
subString has numbers of overloads.
for first string
String first=scz.subString(0,6);
String second=scz.subString(7,9);
You can use following regex to take out the above type string:
\d+[A-Z]\d{2}|[A-Z]{3}|(?<=-)[\d/]+
In Java, you can use above regex in following way:
Pattern pattern = Pattern.compile("\\d+[A-Z]\\d{2}|[A-Z]{3}|(?<=-)[\\d/]+");
Matcher matcher = pattern.matcher("3282E81WHT-22/24");
while (matcher.find()) {
System.out.println(matcher.group());
}
Output:
3282E81
WHT
22/24
You could us a char array instead of a string so you can access specific characters withing the array.
Example
char scz[] = "3282E81WHT-22/24";
and access the separate characters just by specifying the place in which the array you want to use.
You can try this
String scz="3282E81WHT-22/24";
String[] arr=scz.split("-");
System.out.println("first: "+arr[0].substring(0,7));
System.out.println("second: "+arr[0].substring(7,10));
System.out.println("third: "+arr[1])
Check out my solution -
class Main {
public static void main(String[] args) {
String first = "";
String second = "";
String third = "";
String scz="3282E81WHT-22/24";
String[] portions = scz.split("-");
if (portions.length > 1) {
third = portions[1];
}
String[] anotherPortions = portions[0].split("[a-zA-Z]+$");
if (anotherPortions.length > 0) {
first = anotherPortions[0];
}
second = portions[0].substring(first.length());
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Live Demo.
String scz="3282E81WHT-22/24";
String[] array = scz.split("-");
String str1 = (String) array[0].subSequence(0, 7);
String str2 = array[0].substring(7);
Then the split will be in this order :)
str1
str2
array[1]
if the length of string is fixed for scz, first,second and third the you can use
String first=scz.subString(0,6);
String second=scz.subString(7,9);
String third=scz.subString(10,scz.length());
I have a String "Magic Word". I need to trim the string to extract "Magic" only.
I am doing the following code.
String sentence = "Magic Word";
String[] words = sentence.split(" ");
for (String word : words)
{
System.out.println(word);
}
I need only the first word.
Is there any other methods to trim a string to get first word only if space occurs?
String firstWord = "Magic Word";
if(firstWord.contains(" ")){
firstWord= firstWord.substring(0, firstWord.indexOf(" "));
System.out.println(firstWord);
}
You could use String's replaceAll() method which takes a regular expression as input, to replace everything after the space including the space, if a space does indeed exist, with the empty string:
String firstWord = sentence.replaceAll(" .*", "");
This should be the easiest way.
public String firstWord(String string)
{
return (string+" ").split(" ")[0]; //add " " to string to be sure there is something to split
}
modifying previous answer.
String firstWord = null;
if(string.contains(" ")){
firstWord= string.substring(0, string.indexOf(" "));
}
else{
firstWord = string;
}
String input = "This is a line of text";
int i = input.indexOf(" "); // 4
String word = input.substring(0, i); // from 0 to 3
String rest = input.substring(i+1); // after the space to the rest of the line
A dirty solution:
sentence.replaceFirst("\\s*(\\w+).*", "$1")
This has the potential to return the original string if no match, so just add a condition:
if (sentence.matches("\\s*(\\w+).*", "$1"))
output = sentence.replaceFirst("\\s*(\\w+).*", "$1")
Or you can use a cleaner solution:
String parts[] = sentence.trim().split("\\s+");
if (parts.length > 0)
output = parts[0];
The two solutions above makes assumptions about the first character that is not space in the string is word, which might not be true if the string starts with punctuations.
To take care of that:
String parts[] = sentence.trim().replaceAll("[^\\w ]", "").split("\\s+");
if (parts.length > 0)
output = parts[0];
You May Try This->
String newString = "Magic Word";
int index = newString.indexOf(" ");
String firstString = newString.substring(0, index);
System.out.println("firstString = "+firstString);
We should never make simple things more complicated. Programming is about making complicated things simple.
string.split(" ")[0]; //the first word.