Print string up to a certain word - Java - 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);

Related

Java string loop pattern

I'm going through some introductory exercises and I can not understand how to get java to output a string of five letters in the particular pattern shown below.
Initially I thought it followed the tribonacci sequence for number of characters per line. Without just printing the line, I can not figure out how to have java logically replicate the pattern. They seem to copy each other, but don't really follow a pattern.
The strings are palindrome and getting its end from the last string, for example; line 2 has "ABA" string, so line 3 will copy "ABA" at its end and will insert character C in the middle, so the final string will be "ABACABA"
String LastPattern="";
for(int i=0;i<5;i++){
System.out.println( LastPattern + (char)(65+i) +LastPattern);
LastPattern=LastPattern + (char)(65+i) +LastPattern;
}
Maybe this gets you going:
Something
Something New Something
Something New Something Newer Something New Something
The pattern is there, right in front of you.

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

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).

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);

String.contains always appears false

public final void nameErrorLoop () {
while (error) {
System.out.println("Enter the employee's name.");
setName(kb.next());
if (name.contains("[A-Za-z]")) {
error = false;
}
else {
System.out.println("The name can only contain letters.");
}
}
error = true;
}
Despite a similar setup working in a different method, this method becomes stuck in a constant loop because the if statement is always false. I've tried .matches(), and nothing that I found on the Interent has helped so far. Any ideas why? Thanks for your help in advance.
Edit: I just noticed as I was finishing the project, that trying to print 'name' later only shows the first name, and the last is never printed. Is there any way I can get the 'name' string to include both?
String.contains doesn't use regular expressions - it just checks whether one string contains another, in the way that "foobar" contains "oob".
It sounds like you want to check that name only contains letters, in which case you should be checking something like:
if (name.matches("^[A-Za-z]+$"))
The + (instead of *) will check that it's non-empty; the ^ and $ will check that there's nothing other than the letters.
If you expect it to be a full name, however, you may well want to allow spaces, hyphens and apostrophes:
if (name.matches("^[-' A-Za-z]+$"))
Also consider accented characters - and punctuation from other languages.
Easy. .contains() is not what you think. It does exact String matching.
"anything".contains("something that's not a regular expression");
Either use this
Pattern p2=Pattern.compile("[A-Za-z]+");//call only once
p2.matcher(txt).find();//call in loop
or this:
for(char ch: "something".toCharArray()){
if(Character.isAlphabetic(ch)){
}
}

How to scan words in a text without newline character?

I have serious issues to understand how the scanner class works. Indeed, I would like from this input:
AAAA BBBG GREZZ
ADFG GTRE
FREZZ
to have this ouput as an ArrayList:
[AAAA, BBBG, GREZZ, ADFG, GTRE, FREZZ]
My code is the following:
System.out.println("list of words?");
Scanner scan3 = new Scanner(System.in);
scan3.useDelimiter("[\\s+\\n]");
ArrayList<String> test = new ArrayList<String>();
while(scan3.hasNext()){
String temp = scan3.next();
if(temp.equals("STOP")){
break;
}else{
test.add(temp);
}
}
System.out.println(test);
My input is:
AAAA BBBG GREZZ
ADFG GTRE
FREZZ STOP
And my ouput is:
[AAAA, BBBG, GREZZ, , ADFG, GTRE, , FREZZ]
My question is twofold:
Why do I have an empty element inserted in the list (which is I beleive related to the new line)?
As you might have noticed, I add the string "STOP" at the end in order to stop the loop because the condition scan3.HasNext() always returns "true", is it the only way to proceed?
Many thanks for your help.
Just use String#split() with a suitable delimiter (it sounds like in this case you just need "[ \\n]+" (that's a space and a \n) but you may want to tweak that a bit, for example you might want to split on all whitespace.
The reason for the empty entry in the list is because you are just scanning for a single character of whitespace. This gets matched twice when you have two line endings next to each other. You need to modify the regex so it matches more than one character.
Your + appears to be in the wrong place. Try instead using scan3.useDelimiter("[\\s\\n]+");
Regarding,
As you might have noticed, I add the string "STOP" at the end in order to stop the loop because the condition scan3.HasNext() always returns "true", is it the only way to proceed?
What other way would you wish to proceed? What other stop condition do you propose to use?

Categories