Java substring in a string - java

I know this has question has been asked countless times.. but I can't seem to get it to work. the problems are,
Even converting everything to lower case doesn't work out when
"computer" and "Comp" are entered.
If the string is a sentence (I add a space), it essentially skips the substring code and says "Not in the string"..
Help is appreciated.
thanks!
Scanner in=new Scanner(System.in);
System.out.println("\fEnter the main string:");
String GivenString=in.next();
System.out.println("Enter the substring :");
String SubString=in.next();
GivenString.toLowerCase();
SubString.toLowerCase();
if(GivenString.indexOf(SubString)!=-1)
{
System.out.println("Substring is in the given string.");
}
else
{
System.out.println("Substring is not in the given string.");
}

Strings are immutable and toLowerCase() returns a new String object. These lines:
GivenString.toLowerCase();
SubString.toLowerCase();
...do not modify the values in GivenString and SubString.
You would need to modify them to:
GivenString = GivenString.toLowerCase();
SubString = SubString.toLowerCase();

Related

Java - Scanner doesn't read string with space (Solved)

I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris".
What happens with the code below is that the scanner input.next() doesn't allow the mentioned example input string.
I expect this output: Success! but this is the actual output: Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
SOLUTION
The source of the problem is the used scanner method.
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
Explanation: https://stackoverflow.com/a/22458766/11860800
String t = "Chuck Norris";
t.matches("[a-zA-Z ]+")
Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com
Please refer this link :
Java Regex to Validate Full Name allow only Spaces and Letters
you can use the below Regular Expression
String regx = "^[\\p{L} .'-]+$";
This should work for all scenarios and unicode.

How to check string for lettters (numberformatexception)

I have my code and it is able to check for letters on their own, but when i have them together in the same string it just crashes
I've tried the .matches method and ive also tried .contains which i thought would be the best fit but im not sure what would be the best to use.
String regex = "^[a-zA-Z]+$";
System.out.println("How many dice to you want to roll?");
String DiceChoice = scan.nextLine();
while (DiceChoice.indexOf(".")!=-1 || DiceChoice.matches(regex)) {
System.out.println("Please enter a number without a decimal or
letter");
DiceChoice = s.nextLine();
}
int DiceChoiceInt = Integer.parseInt(DiceChoice);
When i put in "a" it is fine, or "." its fine but when i put in "4a" thats when i get the exception.
I expect it to find the letter somewhere in the string and go into the while loop but it just comes up with a number format exception, i was thinking maybe i could do a try catch possibly? Any help is appreciated
The regex pattern for a pure number string is \d+, so why not just check for that positive match instead:
String diceChoice;
do {
diceChoice = scan.nextLine();
if (diceChoice.matches("\\d+")) break;
System.out.println("Please enter a number-only choice");
} while (true);
int diceChoiceInt = Integer.parseInt(diceChoice);
This approach will loop indefinitely until a pure number input happens.

Does my method work for finding each word in a string

As the title suggests, I'm trying to make a method that will individually work on each word of a string. I've gotten the code down but I'm not sure if it is right. So I ran a couple of tests to see if it prints out appropriately. After multiple tries and absolutely nothing printing out. I need help. Can anyone find anything wrong my code?
public static String build( String str4, one test){
Scanner find = new Scanner( System.in);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
return phrase;
}
The method change just changes the word to pig latin ( my intended goal ).
Here are the simple lines in my main method:
String str4 = "I am fluent in pig latin";
System.out.println (test.build(str4, test));
I intended for this code to print out this:
Iyay amyay uentflay inyay igPay atinLay
You attempt to get some input inside your function, using the Scanner instance, giving user input as its construction argument.
In order to print what is going to be returned, add this line:
System.out.println (phrase);
before your return statement.
What I am guessing though, is you are mistakenly using user input.
Try this instead:
public static String build( String str4, one test){
Scanner find = new Scanner(str4);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
//Print your phrase here if you want.
System.out.println(phrase);
return phrase;
}
You have:
Scanner find = new Scanner( System.in);
Which means you're reading from user input.
You also have this str4 parameter, but you're not actually using it. You seem to have inadvertently used System.in as your input string source when you really meant to use your str4 parameter. Hence, nothing happens, as find.next() is waiting for input from the console rather than using the string you passed in.
You probably mean:
Scanner find = new Scanner(str4);

Can I use startsWith and endsWith in Java to check input?

In Java can I use startsWith and endsWith to check a user input string? Specifically, to compare first and last Characters of the input?
EDIT1: Wow you guys are fast. Thank you for the responses.
EDIT2: So CharAt is way more efficient.
So How do I catch the First and last Letter?
char result1 = s.charAt(0);
char result2 = s.charAt(?);
EDIT3: I am very close to making this loop work, but something is critically wrong.
I had some very good help earlier, Thank you all again.
import java.util.Scanner;
public class module6
{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(true){
System.out.print("Please enter words ending in 999 \n");
System.out.print("Word:");
String answer;
answer = scan.next();
char aChar = answer.charAt(0);
char bChar = answer.charAt(answer.length()-1);
String MATCH = new String("The word "+answer+" has first and last characters that are the same");
String FINISH = new String("Goodbye");
if((aChar == bChar));
{
System.out.println(MATCH);
}
if(answer !="999")
{
System.out.println(FINISH);
break;
}
}
}
}
The loop just executes everything, No matter what is input. Where did I go wrong?
In Java can I use startsWith and endsWith to check a user input string?
You certainly can: that is what these APIs are for. Read the input into a String, then use startsWith/endsWith as needed. Depending on the API that you use to collect your input you may need to do null checking. But the API itself is rather straightforward, and it does precisely what its name says.
Specifically, to compare first and last Characters of the input?
Using startsWith/endsWith for a single character would be a major overkill. You can use charAt to get these characters as needed, and then use == for the comparison.
yes, you should be able to do that and it should be pretty striaghtforward. Is there a complexity that you are not asking?
Yes, in fact, not just characters, but entire strings too.
For example
public class SOQ4
{
public static void main(String[] args)
{
String example = "Hello there my friend";
if(example.startsWith("Hell"))
{
System.out.println("It can do full words");
}
if(example.startsWith("H"))
{
System.out.println("And it can also do letters");
}
if(example.endsWith("end"))
{
System.out.println("Don't forget the end!");
}
if(example.endsWith("d"))
{
System.out.print("Don't forget to upvote! ;)");
}
}
}
I recommend you use the API, here's a link to it http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Printing a string backwards

I'm trying to print a string in reverse. i.e.
hello world
should come out as:
dlrow olleh
But the outcome only shows the reverse of the first word. i.e.
olleh
Any thoughts?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Input a string:");
String s;
s = input.next();
String original, reverse = "";
original = s;
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
input.close();
}
}
Using input.next() only stores the next word in the variable (only "hello"). Try this:
System.out.println("Input a string:");
String s;
s = input.nextLine();
System.out.println("entered: " + s);
The line
s=input.next()
will only take one word.
So to get the whole line 'hello world', you've to use the nextLine() function.
s = input.nextLine();
Your scanner object returns only the next complete token through the input.next() method. A token is considered complete when there is a whitespace character. Use the nextLine() method of the scanner to get the complete input if you are using multiple words.
new StringBuilder("hello world").reverse().toString();
Maybe much more simpler.
use s.nextline() instead of s.next() as s.next() read only first token string
Scanner sc= new Scanner(System.in);
String s = sc.nextLine();
System.out.println(new StringBuilder(s).reverse().toString());
From Scanner javadoc:
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
What happens is that the token delimiter may not be what you're expecting (newline, for instance).
If you wish your program to read the entire line input by the user, you might want to use Scanner.nextLine(), which will read the entire line input by the user, or maybe Scanner.next(String delimiter), which will allow you to enter the desired token delimiter.
Change s = input.next() to s = input.nextLine()
I can't really write some source code but maybe try using two different inputs. After that add each string to it's own variable. After that, reverse them both and add them together as an output.

Categories