I have 2 strings "test" "bet" and another string a="tbtetse". I need to check if the "tbtetse" contains the other two strings.
I was thinking if I could find all the anagrams of string a and and then find the other two strings in those, but it doesn't work that way and also my anagram code is failing for a lengthy string.
Could you please help with any other ways to solve it?
Assuming you're trying to test whether the letters in a can be used to form an anagram of the test strings test and bet: I recommend making a dictionary (HashMap or whatever) of character counts from string a, indexed by character. Build a similar dictionary for the words you're testing. Then make sure that a has at least as many instances of each character from the test strings as they have.
Edit: Alcanzar suggests arrays of length 26 for holding the counts (one slot for each letter). Assuming you're dealing with only English letters, that is probably less of a hassle than dictionaries. If you don't know the number of allowed characters, the dictionary route is necessary.
Check below code, it may help you.
public class StringTest {
public static void main(String[] args) {
String str1 = "test";
String str2 = "bev";
String str3 = "tbtetse";
System.out.println(isStringPresent(str1, str2, str3));
}
private static boolean isStringPresent(String str1, String str2, String str3) {
if ((str1.length() + str2.length()) != str3.length()) {
return false;
} else {
String[] str1Arr = str1.split("");
String[] str2Arr = str2.split("");
for (String string : str1Arr) {
if (!str3.contains(string)) {
return false;
}
}
for (String string : str2Arr) {
if (!str3.contains(string)) {
return false;
}
}
}
return true;
}
}
basically you need to count characters in both sets and compare them
void fillInCharCounts(String word,int[] counts) {
for (int i = 0; i<word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
counts[index]++;
}
}
int[] counts1 = new int[26];
int[] counts2 = new int[26];
fillInCharCounts("test",counts1);
fillInCharCounts("bet",counts1);
fillInCharCounts("tbtese",counts2);
boolean failed = false;
for (int i = 0; i<counts1.length; i++) {
if (counts1[i] > counts2[i]) {
failed = true;
}
}
if (failed) {
whatever
} else {
something else
}
If you are generalizing it, don't forget to call .toLowerCase() on the word before sending it in (or fix the counting method).
Pseudo code:
Make a copy of string "tbtetse".
Loop through each character in "test".
Do a indexOf() search for the character in your copied string and remove it if found.
If not found, fail.
Do the same for the string "bet".
class WordLetter {
char letter;
int nth; // Occurrence of that letter
...
}
One now can use Sets
Set<WordLetter>
// "test" = { t0 e0 s0 t1 }
Then testing reduces to set operations. If both words need to be present, a union can be tested. If both words must be formed from separate letters, a set of the concatenation can be tested.
Related
What I want to do is create a method that takes two objects as input
of type String. The method will return logical truth if both strings are the same (word spacing and capitalization do not matter). I thought to split String, make an Array of elements, add each element to List and then compare each element to space and remove it from List. At the end use a compareToIgnoreCase() method. I stopped on removing space from List for string2. It works to string1List and doesn't work to string2List, I'm wondering why?? :(
I will be grateful for help, I spend a lot of time on it and I'm stuck. Maybe someone know a better solution.
import java.util.ArrayList;
import java.util.List;
public class Strings {
public static void main(String[] args) {
String string1 = "This is a first string";
String string2 = "this is a first string";
String[] arrayOfString1 = string1.split("");
List<String> string1List = new ArrayList<>();
for (int i = 0; i < arrayOfString1.length; ++i) {
string1List.add(arrayOfString1[0 + i]);
}
String[] arrayOfString2 = string2.split("");
List<String> string2List = new ArrayList<>();
for (int i = 0; i < arrayOfString2.length; ++i) {
string2List.add(arrayOfString2[0 + i]);
}
for (int i = 0; i < string1List.size(); ++i) {
String character = string1List.get(0 + i);
if (character.equals(" ")) {
string1List.remove(character);
}
}
for (int i = 0; i < string2List.size(); ++i) {
String character = string2List.get(0 + i);
if (character.equals(" ")) {
string2List.remove(character);
}
}
System.out.println(string2List.size());
}
}
You can try below solution. As you mentioned word spacing and capitalization do not matter
1.remove capitalization - using toLowercase()
2.for word spacing - remove all word spacing using removeAll() with regex pattern "\\s+" so it removes all spaces.
3. check both strings now.
public class StringChecker {
public static void main(String[] args) {
System.out.println(checkString("This is a first string", "this is a first string"));
}
public static boolean checkString(String string1, String string2){
String processedStr1 = string1.toLowerCase().replaceAll("\\s+", "");
String processedStr2 = string2.toLowerCase().replaceAll("\\s+", "");
System.out.println(" s1 : " + processedStr1);
System.out.println(" s2 : " + processedStr2);
return processedStr1.equals(processedStr2);
}
}
Your problem has nothing to do with spaces. You can replace them with any other character (for example "a") to test this. Therefore, removing spaces in any of the methods given above will not improve your code.
The source of the problem is iterating the list with the for command. When you remove an item from a list inside the for loop, after removing the i-th element, the next element in the list becomes the i-th current element.
On the next repetition of the loop - when i is incremented by one - the current i + 1 item becomes the next item in the list, and thus you "lose" (at least) one item. Therefore, it is a bad idea to iterate through the list with the for command.
However you may use many other methods available for collections - for instance Iterators - and your program will work fine.
Iterator <String> it = string1List.iterator();
while(it.hasNext())
{
if(it.next().equals("a")) it.remove();
}
Of course there is no need at all to use Lists to compare these two strings.
I have a String with value
String rest="bac";
I have another String with value
String str="baack";
If i use
str.contains(rest);
it returns false. But i want the output to be true. As "baack" contains all the letters from string rest
Is it possible to do so? With or without this method?
Unfortunately, there is no standard method doing this, as far as I know.
If what you want is to check that the second string contains at least once every character of the first string, then you can check each character one by one with the following test:
boolean result = true;
for (char c : test.toCharArray()) {
result &= str.indexOf(c) > -1;
}
return result;
Or alternatively:
for (char c : test.toCharArray()) {
if (str.indexOf(c) == -1) {
return false;
}
}
return true;
It might not be optimal, but it works and it is simple to read.
Since the order is not important, your question turns to be whether the first set of character contains the second set of character.
// Initial the sets
Set<char> bigSet = new HashSet<char>(Arrays.asList(str));
Set<char> smallSet = new HashSet<char>(Arrays.asList(rest));
for (char c : smallSet) {
if(!bigSet.contains(c)){
return false;
}
}
return true;
Here is another way to make sure all characters from one string are in the second string. It is a lengthy way but it is one of the very basic ways to work with characters from String in java. I know it is not optimal but it serves the purpose.
String rest="bac";
String str="baack";
char[] strChar = str.toCharArray();
char[] restChar = rest.toCharArray();
int count = 0;
for(int i=0;i<restChar.length;i++){
for(int j=0;j<strChar.length; j++){
if(restChar[i] == strChar[j]){
count++;
}
}
}
if(count>=restChar.length){
System.out.println("All the characters from: "+rest+" are in: "+str);
}
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );
Okk As programmer we love get involved in logic building but that is not the case some time we become blank over some type of puzzle as below mentioned. Let me declare that this is not any kind of homework or job stuff it simply a logic and performance practice puzzle.Okk the puzzle of given an Strings` with comma separated words like
String S= peas,sugar,rice,soup
Now crux is to find out length of longest chain of the words like last character of word should be the first character of next word and so on to create a longest possible chain and finally to calculate the length of that chain.
Now I had tried to figure out some sort of solution like
split the string with comma
add them in list
sort that list
etc
but now how to develop further logic As I m little poor over logic development,Help is appreciated and if above half logic is not proper as it should be than what must the simple sort and perfect way to get the length of the longest chain of words.
Summary
input: String S= peas,sugar,rice,soup.
output: 4 length of words (peas->sugar->rice->soup) or (soup->peas->sugar->rice) etc
Once you have list (or array) you can iterate over the array checking your condition (equality of last letter of n-th words with the first letter of first word) and increase counter each time. Once the condition is false just escape the loop. Your counter will hold value you need.
okk friends here the logic and core part which I had made and my puzzle got solved
import java.util.Map;
import java.util.Stack;
public class CandidateCode
{
public static int chainLength=0;
public static void main(String[] args) {
String s= "peas,sugar,rice,soup";
int chainLengthfinal=wordChain(s);
System.out.println("final length:"+chainLengthfinal);
}
public static int wordChain(String input1)
{
List<String> stringList = new ArrayList<String>();
stringList= Arrays.asList(input1.split(","));
boolean ischain = new CandidateCode().hasChain(stringList);
if (ischain) {
return chainLength;
}
return 0;
}
Map<Character, List<String>> startsWith = new HashMap<Character, List<String>>();
Map<Character, List<String>> endsWith = new HashMap<Character, List<String>>();
private Character getFirstChar(String str) {
return str.charAt(0);
}
private Character getLastChar(String str) {
return str.charAt(str.length() - 1);
}
boolean hasChain(List<String> stringList) {
for (String str : stringList) {
Character start = getFirstChar(str);
Character end = getLastChar(str);
List<String> startsWithList;
List<String> endsWithList;
if (startsWith.containsKey(start)) {
startsWithList = startsWith.get(start);
} else {
startsWithList = new ArrayList<String>();
startsWith.put(start, startsWithList);
}
if (endsWith.containsKey(end)) {
endsWithList = endsWith.get(end);
} else {
endsWithList = new ArrayList<String>();
endsWith.put(end, endsWithList);
}
startsWithList.add(str);
endsWithList.add(str);
}
Stack<String> stringStack = new Stack<String>();
for (String str : stringList) {
if (hasChain(stringList.size(), str, stringStack)) {
System.out.println(stringStack);
System.out.println("size "+stringStack.size());
chainLength= stringStack.size();
return true;
}
}
return false;
}
private boolean hasChain(int size, String startString, Stack<String> stringStack) {
if (size == stringStack.size()) return true;
Character last = getLastChar(startString);
if (startsWith.containsKey(last)) {
List<String> stringList = startsWith.get(last);
for (int i = 0; i < stringList.size(); i++) {
String candidate = stringList.remove(i--);
stringStack.push(candidate);
if (hasChain(size, candidate, stringStack)) {
return true;
}
stringStack.pop();
stringList.add(++i, candidate);
}
}
return false;
}
}
output of the above program will be
[soup, peas, sugar, rice]
size 4.
final length:4.
initialize a " " string named last(String last=" ")
get the first string by splitting with comma
substring the last char of the string and store it to last
boolean brokenchain=false;
length=0;
while(more string to split with comma)&&(!brokenchain){
split string with comma
substring to get first char
if(first char!=last){
brokenchain=true;
}else{
length++;
get last char of this string with substring and store it to last
}
}
if you have for input a sequence of legth 5 and the it brokes and there is a sequence of length 6 following which you want to count and print as output, you have to store the count variable in a map, for example, as a key associated with the sequence as far. then you continue the loop(you have to make the brokenchain=false again) until the input string sequence ends. then you get the bigger key from your map and print it with his associated value(the biggest sequence)
I think you need to find the largest and smallest number.
split the string with comma
add them as list_item
compare list_item1 and list_item2, the largest value becomes list_item_X
compare list_item3 and list_item4, the largest value becomes list_item_Y
Now compare list_item1 and list_item_X, the largest value becomes
So the largest value is list_item_Z, here is implimentation through code.
$s = 'peas,sugar,rice,soup';
$list_items = explode(',', $s);
$lengths = array_map('strlen', $list_items);
echo "The shortest is " . min($lengths) .
". The longest is " . max($lengths);
May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools
"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");`
but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.
Part of My Java code
public String proc_MODEL(Element recElement)
{
String SEAT = "";
try
{
SEAT = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500
if (SEAT.length()>0)
{
SEAT = SEAT.replaceFirst("^0*", ""); //I need to remove leading zero to only 500
}
catch (Exception e)
{
e.printStackTrace();
return "501 Exception in proc_MODEL";
}
}
}
Appreciate for help.
If you want remove leading zeros, you could parse to an Integer and convert back to a String with one line like
String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);
Output is
1
Of course if you intend to use the value it's probably better to keep the int
int s = Integer.parseInt(seat);
System.out.println(s);
replaceFirst() was introduced in 1.4 and your compiler pre-dates that.
One possibility is to use something like:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
while ((s.length() > 1) && (s.charAt(0) == '0'))
s = s.substring(1);
System.out.println(s);
}
}
It's not the most efficient code in the world but it'll get the job done.
A more efficient segment without unnecessary string creation could be:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
int pos = 0;
int len = s.length();
while ((pos < len-1) && (s.charAt(pos) == '0'))
pos++;
s = s.substring(pos);
System.out.println(s);
}
}
Both of those also handle the degenerate cases of an empty string and a string containing only 0 characters.
Using a java method str.replaceAll("^0+(?!$)", "") would be simple;
First parameter:regex -- the regular expression to which this string is to be matched.
Second parameter: replacement -- the string which would replace matched expression.
As stated in Java documentation, 'replaceFirst' only started existing since Java 1.4 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
Use this function instead:
String removeLeadingZeros(String str) {
while (str.indexOf("0")==0)
str = str.substring(1);
return str;
}