Checking if a String Contains Another, if so at what Indexes - java

I have not been able to find a solution to this online, StackOverflow or elsewhere, so I thought I'ld post here.
Suppose there's a string called String1. There are also many other strings, such as StringA, String B, StringC... StringZ.
String1 will contain only one of those strings (StringA-Z), and it may contain extra characters in front and behind it (in a sense, StringA-Z is hidden within String1)
Now, how would one check which StringA-Z is contained within String1, and at what indexes, so it would be possible to trim String1 (or leave it as is if that's the case) in a way that it ends up matching the string it contained?
Thanks
- cp15
EDIT: Solved. Thanks to everyone who replied. Looks like there were other questions like this on StackOverflow, I remember reading one or two, but I thought my case was different. Turns out I was just confusing indexOf() with substring().

How about using indexof method?
If (string1.indexof(stringA) != -1){
// it does exists. Do something with it..
}
Just of the top of my head, but if i understand you correctly then this should be enough

I'm not sure why you would use a HashMap in which every key maps to itself, so I'm going to just use a list of Strings (stringList) to show how to do this.
for (String stringX : stringList) {
// Get the starting index of stringX in string1
int index = string1.indexOf(stringX);
// index will be -1 if stringX is not within string1
if (index != -1) {
// Do what you want here, then break since there is only one match
// and we already found it.
break;
}
}
If you really wanted to use a HashMap (I'll call it stringMap), simply change stringList to stringMap.keySet() or stringMap.values() (since they are both the same).

Related

Why is my String array length 3 instead of 2?

I'm trying to understand regex. I wanted to make a String[] using split to show me how many letters are in a given string expression?
import java.util.*;
import java.io.*;
public class Main {
public static String simpleSymbols(String str) {
String result = "";
String[] alpha = str.split("[\\+\\w\\+]");
int alphaLength = alpha.length;
// System.out.print(alphaLength);
String[] charCount = str.split("[a-z]");
int charCountLength = charCount.length;
System.out.println(charCountLength);
}
}
My input string is "+d+=3=+s+". I split the string to count the number of letters in string. The array length should be two but I'm getting three. Also, I'm trying to make a regex to check the pattern +b+, with b being any letter in the alphabet? Is that correct?
So, a few things pop out to me:
First, your regex looks correct. If you're ever worried about how your regex will perform, you can use https://regexr.com/ to check it out. Just put your regex on the top and enter your string in the bottom to see if it is matching correctly
Second, upon close inspection, I see you're using the split function. While it is convenient for quickly splitting strings, you need to be careful as to what you are splitting on. In this case, you're removing all of the strings that you were initially looking at, which would make it impossible to find. If you print it out, you would notice that the following shows (for an input string of +d+=3=+s+):
+
+=3=+
+
Which shows that you accidentally cut out what you were looking to find in the first place. Now, there are several ways of fixing this, depending on what your criteria is.
Now, if what you wanted was just to separate on all +s and it doesn't matter that you find only what is directly bounded by +s, then split works awesome. Just do str.split("+"), and this will return you a list of the following (for +d+=3=+s+):
d
=3=
s
However, you can see that this poses a few problems. First, it doesn't strip out the =3= that we don't want, and second, it does not truly give us values that are surrounded by a +_+ format, where the underscore represents the string/char you're looking for.
Seeing as you're using +w, you intend to find words that are surrounded by +s. However, if you're just looking to find one character, I would suggest using another like [a-z] or [a-zA-Z] to be more specific. However, if you want to find multiple alphabetical characters, your pattern is fine. You can also add a * (0 or more) or a + (1 or more) at the end of the pattern to dictate what exactly you're looking for.
I won't give you the answer outright, but I'll give you a clue as to what to move towards. Try using a pattern and a matcher to find the regex that you listed above and then if you find a match, make sure to store it somewhere :)
Also, for future reference, you should always start a function name with a lower case, at least in Java. Only constants and class names should start in a capital :)
I am trying to use split to count the number of letters in that string. The array length should be two, but I'm getting three.
The regex in the split functions is used as delimiters and will not be shown in results. In your case "str.split([a-z])" means using alphabets as delimiters to separate your input string, which makes three substrings "(+)|d|(+=3=+)|s|(+)".
If you really want to count the number of letters using "split", use 'str.split("[^a-z]")'. But I would recommend using "java.util.regex.Matcher.find()" in order to find out all letters.
Also, I'm trying to make a regex to check the pattern +b+, with b being any letter in the alphabet? Is that correct?
Similarly, check the functions in "java.util.regex.Matcher".

Take first half of first string, and put it at beginning of second string based on user input

I am at the beginning chapters in my Java I class. This seems beyond what I have learned thus far.
I have to ask a user to input the first string. It could be anything. Then they have to input a second string. I have to take the first half of the first string and place it in front of the second string, then the other half of the first string and place it at the end of the first string. For example:
Enter something: ----
Enter something: word
Output: --word--
The only thing I've learned up until now is concatenation, indexes, and getting length. I have not learned arrays, if they can be relevant to this. What methods would I use to split this string up when I only know the strings after the user enters them? Even just informing me of unknown method calls would lead me in the right direction. I don't want (and can't) copy anyone's code.
Based on your example this is how you achieve that:
String firstString = "----"; //this should be read in from the user input.
String secondString = "word"; //this too should be read in from the user.
String finalString = firstString.substring(0,firstString.length()/2)+secondString+firstString.substring(firstString.length()/2,firstString.length());
Test code here
You should look into the Java StringAPI for substring. This will help you understand the code above.
You can use the substring method of the String class
something like this should work:
int idxMiddle = (string1.length()-1)/2;
string1.substring(0,idxMiddle) + string2 + string1.substr(idxMiddle);

Splitting strings like push1234 in java

So, please bear with me as I have a long question here, I have some code in java that is using an array list to implement a stack. I need to be able to enter the command "push" to add stuff to the stack. However my problem is that it has to be in the format pushSTUFF.
Where the "STUFF" is anything, upper case, lower case, string, int, etc.. The way I've been trying to implement this is with the string split method where PUSH is the delimiter. Then the command is passed to a switch case.
I quickly realized that the split gets discarded, at least as far as I can tell, and that the switch case is getting pushSTUFF not push as the case input.
In contemplating this problem I came up with a couple of ways I could do this. I just don't know if they are possible or how to do them.
So,
Is there a way to split a string like pushSTUFF and keep both parts (the push and the STUFF)
Is there a way to split, from a string, something of unknown length or contents (since I don't know what the user will input the STUFF is unknown)
Is there a way to tell the switch case to look for the pushSTUFF as opposed to just push (again because STUFF is unknown).
Are any of these even possible to do? If so what would you recommend?
I'm sure there are better ways but as I'm still learning java these seemed like the best for right now. Also I didn't post any code because I didn't feel it was necessary to the question. I will post some if you need it though. Just ask and I will be happy to oblige.
(tl;dr) Is it possible to do any of 1, 2, or 3 above and if so how?
Thanks in advance.
Instead of splitting the strings, you can use regular expressions with groups and iterate over the matching parts of it (as you saw, the split character(s) get discarded).
For #1, you could do something like (pseudocode):
regex = (push)(.*)
stuff = groups[1]
That should also cover #2 since it will match all characters after the push.
I'm not entirely sure what you're asking in #3.
There is a regex tutorial here if you're not familiar with java regular expressions.
You can also take a look at the StringTokenizer, which has an option to keep delimiters.
If the format will always be push*SOMETHING* why aren't you using String.substring()?
You can do:
String something = "pushSTUFF".substring(4);
This way, you will always get whatever is behind push.
I really don't understand what you are trying to achieve without seeing the actual code, but your problem seems simple enough to be solved this way.
Use .indexOf and find push:
public class splitstring {
public static void main(String[] args){
String tosplit, part1, part2 = new String();
int ind = 0;
tosplit = "push1234";
ind = tosplit.indexOf("push");
part1 = tosplit.substring(ind,ind + 4);
part2 = tosplit.substring(ind + 4, tosplit.length());
}
}
You can search for any Uppercase letter and use String.substring(...)
Find if first character in a string is upper case, Java

Print string up to a certain word - Java

I was wondering in Java how I could print a string until it reaches the word "quit" in that string and then instantly stop printing at that point. For instance if the string value was:
"Hi there this is a random string quit this should not be printed"
All that should be printed is "Hi there this is a random string".
I was trying something like this, but I believe it to be wrong.
if ( input.indexOf( "quit" ) > -1 )
{
//code to stop printing here
}
Instead of thinking about the problem as "how to stop printing" (because once you start printing something in Java it's pretty hard to stop it), think about it in terms of "How can I print only the words up to a certain point?" For example:
int quit_position = input.indexOf("quit");
if (quit_position >= 0) {
System.out.println(input.substring(0, quit_position));
} else {
System.out.println(input);
}
Looks like homework, so this answer is in homework style. :-)
You're on the right track.
Save the value of that indexOf to an integer.
Then it's like you have a finger pointing at the right spot - ie, at the end of the substring you really want to print.
That's a hint anyway...
EDIT: Looks like people are giving it to you anyway. But here are some more thoughts:
You might want to think about upper and lower case as well.
Also consider what you are going to do if 'quit' is not there.
Also the solutions here don't strictly solve your problem - they'll print unnecessary spaces too, after the last word ends, before 'quit' starts. If that is a problem you consider String Tokenization or an adapation of the replaceAll solution above to cover for leading whitespace into `quit'.
This has a one-line solution:
System.out.println(input.replaceAll("quit.*", ""));
String.replaceAll() takes a regex to match, which I've specified to be "the literal 'quit' and everything following", which is to be replaced by a blank "" (ie effectively deleted) from the returned String
If you don't mind trailing spaces in your string
int index = input.indexOf("quit");
if (index == -1) index = input.length();
return input.substring(0, index);

How do I split a concatenated string into multiple floating point values?

I'm a begginer in java I have
packet=090209153038020734.0090209153039020734.0
like this I want to split this string and store into an array like two strings:
1) 090209153038020734.0
2) 090209153039020734.0
I have done like this:
String packetArray[] = packets.split(packets,Constants.SF);
Where:
Constants.SF=0x01.
But it won't work.
Please help me.
I'd think twice about using split since those are obviously fixed width fields.
I've seen them before on another question here (several in fact so I'm guessing this may be homework (or a popular data collection device :-)) and it's plain that the protocol is:
STX (0x01).
0x0f.
date (YYMMDD or DDMMYY).
time (HHMMSS).
0x02.
value (XXXXXX.X).
0x03.
0x04.
And, given that they're fixed width, you should probably just use substrings to get the information out.
The JavaDoc of String is helpful here: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
You have your String packet;
String.indexOf(String) gives you a position of a special substring. your interested in the "." sign. So you write
int position = packet.indexOf(".")+1
+1 becuase you want the trailing decimal too. It will return something 20-ish and will be the last pos of the first number.
Then we use substring
String first = packet.substring(0,position) will give you everything up to the ".0"
String second = packet.substring(position-1) should give you everything starting after the ".0" and up to the end of the string.
Now if you want them explicitely into an array you can just put them there. The code as a whole - I may have some "off by one" -bugs.
int position = packet.indexOf(".")+1
String first = packet.substring(0,position)
String second = packet.substring(position-1)
String[] packetArray = new String[2];
packetArray[0] = first;
packetArray[1] = second;
String packetArray[] = packets.split("\u0001");
should work. You are using
public String[] split(String regex, int limit)
which is doing something else: It makes sure that split() returns an array with at most limit members (1 in this case, so you get what you ask for).
You need to read the Javadocs for the String.split() methods...you are calling the version of String.split() that takes a regular expression and a limit, but you are passing the string itself as the first parameter, which doesn't really make sense.
As Aaron Digulla mentioned, use the other version.
You don't say how you want to do the split. It could be based on a fixed length (number of characters) or you want one decimal place.
If the former you could do packetArray = new String[]{packet.substring(0, 20), packet.substring(21)};
int dotIndex = packets.indexOf('.');
packetArray = new String[]{packet.substring(0, dotIndex+2), packet.substring(dotIndex+2)};
Your solution confuses the regexp with the string.
split uses regular expressions as documented here. Your code seems to be trying to match the whole string Constants.SF = 0x01 times, which doesn't make much sense. If you know what char the boxes are then you can use something like {[^c]+cc} where c is the character of the box (i guess this is 0x01), to match each "packet".
I think you are trying to use it like the .net String.Split(...) function?

Categories