Removing inserted numbers from a String in java - java

Ok, so i have created a program that defines if the inserted word is a palindrome or not.
But i need help on removing numbers that where to be inserted in the string.
import java.util.*;
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
String reverse = "";
Scanner scan = new Scanner(System.in);
System.out.print("Type a sentence and press enter: ");
String input = scan.nextLine();
// use regex to remove the punctuation and spaces
String Input = input.replaceAll("\\W", " ");
System.out.println(Input);
int length = input.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse.replaceAll("\\W", "") + input.charAt(i);
System.out.println(reverse);
if (input.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}

If you want to remove digits, try input.replaceAll("[0-9]","")

Try this........
public class T1 {
public static void main(String[] args){
String s = "1234ajhdhols233adfjal";
String[] arr = s.split("\\d");
String sx = new String();
for(String x : arr){
sx = sx+x;
}
System.out.println(sx);
}
}

Example:
public static void main(String[] args) {
String s = "1234ajhdhols233adfjal";
String str = s.replaceAll("\\d", "");
System.out.println(str);
}

Related

Java Splitting Strings and Applying A Method

I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc

Accept a sentence and print the words that have same consecutive characters

Here is my homework:
accept a sentence and print the words that have consecutive characters equal
INPUT: an apple a day keeps
OUTPUT: apple keeps
Here is what I am working on:
import java.util.*;
public class Program1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
int l,i=0; char c,d;int a,b,m=0;int n=0; String r=""; String res="";
l=s.length();
str=" "+str+" ";
for(i=0;i<(l-1);i++)
{
c=str.charAt(i);
d=str.charAt(i+1);
a=c;
b=d;
m=str.indexOf(' ');
n=str.indexOf(' ',(i+1));
if(d==' ')
{
m=str.indexOf(' ',(i-1));
n=str.indexOf(' ',(i+1));
}
if(a==b)
{
r=str.substring(m,n);
res=res +" "+ r;
}
}
System.out.println(res);
}
}
It gets compiled, but it does not give correct output.
If I enter the above example, it returns:
an apple an apple a day keeps
What do I need to do?
You can do something like this to achieve the result,
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String str = s.toLowerCase();
String[] words = str.split(" "); // Split the sentence into an array of words.
for(String ss : words){
char previousChar = '\u0000';
for (char c : ss.toCharArray()) {
if (previousChar == c) { // Same character has occurred
System.out.println(ss);
break;
}
previousChar = c;
}
}
The problem is in the line:
m=str.indexOf(' ');
you start aat the beginning of the sentence every time, so you print the sentence from beginning to the word you want.
This is my proposal. :-D
Input: mi aasas es mass pp
Output: aasas mass pp
import java.util.*;
public class code10
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
String cadena = str;
String delimitadores= "[ .,;?!¡¿\'\"\\[\\]]+";
String[] palabrasSeparadas = cadena.split(delimitadores);
for(int x=0; x<palabrasSeparadas.length; x++)
{
char[] tmpstr = palabrasSeparadas[x].toCharArray();
for(int y=0; y<tmpstr.length; y++)
{
if((y+1) < tmpstr.length)
{
if(tmpstr[y] == tmpstr[y+1])
{
System.out.print(palabrasSeparadas[x] + " ");
}
}
}
}
System.out.println("");
}
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Java program involving substring() and charAt() methods

My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}

Getting the number of occurrences of one string in another string

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.
Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}
You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.

Categories