Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to split a string in different groups but I have no experience in this task.
So I need a regular expression that in Java divides the original string in two groups
A sample of my text is:
calcani k a l k a n i
I want t:
Group 1: calcani
Group 2: k a l k a n i (or, if possible, kalkani)
Any idea of how to create this pattern?
Thank you!
String x="calcani k a l k a n i";
String []x1=x.split(" ",2);
System.out.println(x1[0]);
System.out.println(x1[1]);
output
calcani
k a l k a n i
if you want output like below
calcani
kalkani
then use
String x="calcani k a l k a n i";
String []x1=x.split(" ",2);
System.out.println(x1[0]);
System.out.println(x1[1].toString().replace(" ", ""));
Why regex. Just implement this logic:
Search first space and take substring on left of the first space
Rest of the string on right of first space is your 2nd match, at that point if you want to remove all the spaces you can use:
String repl = str.replace(" ", "");
Use the second argument in the String.split() method to control the maximum number of substrings generated by splitting a string:
String[] temp = "calcani k a l k a n i".split(" ", 2);
Try this,
String[] results = "calcani k a l k a n i".split(" ", 2);
System.out.println(results[0]);
System.out.println(results[1].replace(" ", ""));
You will get both the string as follow:
String[] results = "calcani k a l k a n i".split(" ", 2);
//remove spaces from second group
String secondGroup=result[1];
secondGroup=secondGroup.replaceAll(" ","");
System.out.println("result[0] ->"+result[0]);
System.out.println("result[1] ->"+result[1]);
OutPut
result[0] ->calcani
result[1] ->kalkani
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
For example, string = "ABCDEFGH". if n=2, then output should be "BADCFEHG"; if n=3, output should be "CBAFEDHG".
I know i should use stringbuilder to reverse, but how can i split the string to n parts and then reverse each part?
I will not give you a code for this, you need to learn by trying.
Do this requirement step by step :
how to read that String block by block : String.substring(int, int) in a loop. You need to understand how to calculate the boundery of each blocks
how to reverse a String : see about Reverse a String in JAVA
create the output by mixing those two steps.
Don't try to do everything in once. Find how to do those two separatly, then put the logic together. This is quite simply in the end.
String newStr="";
String oldStr = "ABCDEFGH";
for(int i =0; i<oldStr.length();i+=n) {
if(i+n >= oldStr.length()){
n = oldStr.length()-i;
}
newStr += new StringBuilder(oldStr.substring(i,i+n)).reverse().toString();
}
Edit: Sorry for missreading your question, this little loop does what you're asking for!
What we are doing here is making oldString.length() / n iterations to split the String in n portions. Because the length might not be dividable by your n we have to check if i+n wont be larger than the length of your word (eventually creating a IndexOutOfBoundsException). If this is the case we just set n so that it adds to i to the rest of the word. Hope that explains it well.
I've given you most of the code but it's unfinished. You will have to understand what I left out and how to fix it to complete the problem.
String originalString = someString; //String from user
String tempString = ""; //String used for temporary reasons
String finalString = ""; //Your end result
int n = someNumber; //Number from user
//Loops through the original string, incrementing by n each time
for (int i = 0; i < originalString.length() - n; i += n)
{
//Gives us the current substring to reverse
tempString = originalString.substring(i, i + n);
//Starts at end of substring and adds each char to the final string
for (j = n - 1; j >= 0; j--)
{
finalString += tempString.charAt(j);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
please help me find the code for getting the next character in the string
for example:
input string = "abcd"
output string = "bcde"
I can able to iterate only one character at the time.
thanks in advance
Get the ASCII of the last character in the String and increase the ASCII value by 1.
try this,
String sample = "abcd";
int value = (int) sample.charAt(sample.length() - 1); // here you get the ASCII value
System.out.println("" +((value < ((int)'z')) ? sample.substring(1) + (char) (value + 1) : sample));
Simply add one to the char values:
char[] chars = "abcd".toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] += 1;
}
String nextChars = new String(chars);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to find all three letter substrings from a string in Java.
For example from the string "example string" I should get "exa", "xam", "amp", "mpl", "ple", "str", "tri", "rin", "ing".
I tried using the Java Regular expression "([a-zA-Z]){3}" but I only got "exa", "mpl", "str", "ing".
Can someone tell me a regex or method to correct this.
Implementing Juvanis' idea somewhat, iterate to get your substrings, then use a regular expression to make sure the substring is all letters:
String s = "example string";
for (int i = 0; i <= s.length() - 3; i++) {
String substr = s.substring(i, i + 3);
if (substr.matches("[a-zA-Z]+")) { System.out.println(substr); }
}
When a character is consumed in one regex, it cannot be used in other regexes. In your example, a is consumed in exa so amp will not be listed as output. You should try traditional iterative approach. It is easier to implement.
try this
Matcher m = Pattern.compile("([a-zA-Z]){3}").matcher("example string");
for (int i = 0; m.find(i); i = m.start() + 1) {
System.out.print(m.group() + " ");
}
output
exa xam amp mpl ple str tri rin ing
This can be done using regex as follows:
Find the position of all matches for the string using the regex \w(?=\w\w). This will give you the start index of the first character of each required sub-string.
In this case, you would get: 0, 1, 2, 3, 4, 8, 9, 10 and 11.
Get what you need by taking the sub-strings starting from each position going upto that plus 2.
In this case, that would mean, my_string.substring(0,3), my_string.substring(1,4) and so on, as the begin index parameter is inclusive while the end index parameter is exclusive.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string containing this:
D:\ptc\Windchill_10.0\Windchill\wtCustom\wt\lifecycle\StateRB.rbInfo.
I want to get just this part:
wt\lifecycle\StateRB
How can I do that?
You can simply spilt whole path to parts and then get the parts you want.
String path = "D:\ptc\Windchill_10.0\Windchill\wtCustom\wt\lifecycle\StateRB.rbInfo";
String[] parts = path.split("\\");
parts = Arrays.copyOfRange(parts, parts.length-3, parts.length);
Or you can get throught string using loop (this seems to be better)
int index = 0, i = 0;
Stack<String> al = new Stack<String>();
while((index = path.lastIndexOf()))!=-1 && i < 3) {
al.push((path = path.substring(index)));
i++;
}
String[] parts = (String[])al.toArray(); //if you don't have array elements
// in correct order, you can use
// Collections.reverse with Arrays.asList
// applied on array
You can use string tokeniezer with \ delimiter and fetch only last three string tokens. i hope that above path going to be constant always.
http://www.tutorialspoint.com/java/java_string_substring.htm
Check the above link
example :
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.substring(10) );
System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a String that looks like:
"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!".
I want to count the number of times is is in the string.
How can I do this in Java?
An easy way is using Apache StringUtils countMatches
StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");
int index = input.indexOf("is");
int count = 0;
while (index != -1) {
count++;
input = input.substring(index + 1);
index = input.indexOf("is");
}
System.out.println("No of *is* in the input is : " + count);
If you prefer regex, here is a regex solution:
String example = "Hello my is Joeseph. It is very nice to meet you. isWhat a wonderful day it is!";
Matcher m = Pattern.compile("\\bis\\b").matcher(example);
int matches = 0;
while(m.find())
matches++;
System.out.println(matches);
In this case the "is" in "isWhat" is ignored, because of the \b boundary matcher in the pattern
String haystack = "Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!";
haystack.toLowerCase();
String needle = "is";
int numNeedles = 0;
int pos = haystack.indexOf(needle);
while(pos >= 0 ){
pos = pos + 1;
numNeedles = numNeedles + 1;
pos = haystack.indexOf(needle,pos);
}
System.out.println("the num of " +needle+ "= " +numNeedles);
split on every " " (blank) and check the outcoming string[] with a loop
You can find the code here.
It strangely looks like the Robby's one.
This takes into account the length of "replace"
String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)