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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to write a regular expression for a number with padding spaces. The total length is four.
For example:
( 1)
( 43)
( 232)
(1239)
What I'm currently doing is list all the four cases and combined them with "|". There should be a better way to do it.
Maybe {min, max} could do the job?
Can anyone give some help?
Edit:
With the help of you guys, I get it now. It's ^(?= *\d*$)[\d ]{4}$
Thanks a lot!
If you can't use this regex, you can use Patterns for example :
String str = "( 123)";
int paddingLength = 5;
Pattern p = Pattern.compile("\\((\\s*)(\\d*)\\)");
Matcher m = p.matcher(str);
if (m.find() && m.group(1).length() + m.group(2).length() == paddingLength) {
System.out.println("Match");
} else {
System.out.println("Not Match");
}
Or like #Mad Physicist mention in comment you can use :
if (m.find() && m.group(0).length() - 2 == paddingLength) {
If your string match the regex, and the length of the first group plus the length of the second group equal to the real length then print match, else not match
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've got this string:
"type":"image","originX":"center","originY":"center","left":135,"top":259,"width":270,"height":519,"fill":"rgb(0,0,0)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"src":"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg","filters":[]},
each part is seperated by a comma, i want to be able to extract a few of the numbers into doubles. The ones i want are left, top, scaleX, scaleY and angle. How shall i approch this?
thanks
If you don't want to rely on using JSON parsers (you should, though, if you are using JSON a lot), you could use the split-method on the entire string and split according to , (comma), find the chunks of data that you want, split those according to : and read the data directly from the 2nd slot in the resulting array.
You may need to substring the last " to be able to parse the numbers directly, though.
But like I said, you really do want to use a JSON parser of some kind if you are using JSON more than a few times in your program.
Code example:
String abc = "ABC:123,DEF:456,GHI:789";
String[] chucks = abc.split(",");
String[] oneToThree = chunks[0].split(":");
String nums = oneToThree[1];
System.out.println(nums);
//This will print 123
I know that someone already replied, but I've been doing this, hope that help too:
public class HelloWorld{
public static void main(String []args){
String text ="\"type\":\"image\",\"originX\":\"center\",\"originY\":\"center\",\"left\":135,\"top\":259,\"width\":270,\"height\":519,\"fill\":\"rgb(0,0,0)\",\"overlayFill\":null,\"stroke\":null,\"strokeWidth\":1,\"strokeDashArray\":null,\"strokeLineCap\":\"butt\",\"strokeLineJoin\":\"miter\",\"strokeMiterLimit\":10,\"scaleX\":1,\"scaleY\":1,\"angle\":0,\"flipX\":false,\"flipY\":false,\"opacity\":1,\"shadow\":null,\"visible\":true,\"clipTo\":null,\"src\":\"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg\"";
//Just left and scaleX for example
String left = readValue(text, "left");
String scaleX = readValue(text, "scaleX");
System.out.println("left:" + left);
System.out.println("scaleX:" + scaleX);
}
public static String readValue(String text, String key)
{
//search for the init of the value
int start = text.indexOf("\"" + key + "\"");
//search for the end of the value
int end = text.indexOf(",", start + key.length() + 3);
//return the value. these + 3 , is for quotes and ":"
return text.substring(start + key.length() + 3,end);
}
}
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 want to know how to count the occurrences of a particular sub-string in a string without using any of the built in JAVA string functions. For example:
InputString = "knowbutuknow"
subString = "know"
The program should return the result as 2.
EDIT: Re-phrased my question. This is one of those interview questions I came across.
EDIT: Basic string functions like charAt and length can be used here.
Assuming, you already know the keyword you are searching for:
Start at char "0" of Input String
Iterate until "length - keyWordLength" (keyword of length 4 can not match into the last 3 chars)
Inside: Iterate from 0 to keyWord.length -1 and always compare:
Char at Position of outer loop PLUS position of inner loop of the Input string with the char at "inner loops" position of the keyword.
if you find a match, go ahead with the innerloop, if it does not match, advance the outer loop, by simple "breaking" the inner loop.
If you have a match, and completely processed the inner loop, you have a match of that keyword.
Something like this. I'm Assuming String.length to be allowed. Otherwhise you would need to create your own strlen function. (This can be achieved, using a forach loop and simple counting "up")
This is untested and may not work out of the box, but should give you a brief idea.
String inputString = "knowbutuknow";
String subString = "know";
int matches = 0;
for (int outer = 0; outer <= inputString.length() - subString.length(); outer++){
for (int inner = 0; inner < subString.length(); inner++){
if (inputString.charAt(outer + inner) == subString.charAt(inner)){
// letter matched, proceed.
if (inner == subString.length()-1){
//last letter matched, so a word match at position "outer"
matches++;
//proceed with outer. Room for improvement: Skip next n chars beeing
// part of the match already.
break;
}
}else{
//no match for "outer" position, proceed to next char.
break;
}
}
}
edit: Sorry, mixed in some php :) fixed it.
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make a function that outputs every case possible of a string. The function must output each variation of a string and keep a counter for that variation. For example in no particular order:
C.d
C>d
C>D
C.D
c.d
c.D
c>D
c>d
So far I have this:
public int allCase(String data)
{
int count=0; // counter for the amount of case changes completed
int size= data.length();// length of incoming string
char c[]= data.toLowerCase().toCharArray();
double maxpos=Math.pow(2,size);
System.out.println("Maximum possibilities= "+maxpos);
for(int i=0;i<size;i++)
{
if (c[i]> 33 && c[i]<64) // if the character is special characters !##$%^&*()_<>?,./
{ // prints characters in front and behind of special character
System.out.println( data.substring(0,i)+((char)(c[i]+16))+data.substring(i+1));
}
else{
// output the string variation
}
count++;
}
return count;
}
You can handle the alphabetic characters as a group, adding or subtracting 32, but the rest of the mappings aren't regular enough to beat a table lookup.
Keep two parallel strings:
shifted = "ABCDEFGHIJKLMNOPQRSTUVWXYZ~!##$%^&*()_+|<>?:\"{}";
unshifted = "abcdefghijklmnopqrstuvwxyz`1234567890-=\,./;'[]";
Then, find each character in one or the other string with .indexOf(). Find the opposite shift at the same index in the other string. If a character isn't in either string, then it's a space or another character that isn't part of a shifted/unshifted pair. The total number of strings to generate is then 2^(number of chars found in one of those strings).
Speaking of powers of 2, using Math.pow() is a lousy way to compute small powers of 2. Use 1L<<n instead of Math.pow(n) for integers 0 <= n <= 62, or even 1<<n for 0<=n<=30 if you're able to live with only being able to print out a billion or so strings.
You can make an iterative version, looping from an index value of 0 to (2^n)-1, where n the length of the input string, and then loop for k=0 to (n-1) testing bit k of the outer loop index value to see whether to print upper or lowercase version of the character. I didn't see it before, but Hot Licks has a comment about using this approach. To perform that test, observe that index&(1<<k) is nonzero if and only if bit k is set in (index).
A recursive version is much simpler, but I suspect you'll learn about that later.