reverse every word of the sentence..the changes do not appear - java

this is a simple program to reverse each word of the string and print ... i dont know whats going wrong with this...please help
import java.util.Scanner;
public class ReverseWordCapitalizeFirstCharacter {
public static void reverse(char a[], int start, int end)
{
while(start<end)
{
char temp = a[start];
a[start] = a[end];
a[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner sc = new Scanner(System.in);
String str = sc.next();
char a[] = new char[str.length()];
a = str.toCharArray();
int wordStartIndex = 0;
for(int i=0; i<a.length; i++)
{
if(a[i] == ' ')
{
reverse(a,wordStartIndex,i-1);
wordStartIndex = i+1;
}
}
for(int i=0; i<a.length; i++)
{
System.out.print(a[i]);
}
}
}
i am passing the character array as parameter to the function that reverse each word..

Is it not because sc.next() returns only the next word ?
So, you never encounter a ' ' in your string, thus you never call the reverse method. Try with sc.nextLine(); maybe.

Javadoc says :
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
As a result, if you enter "abc 123 456", sc.next() will only return "abc".
String str = sc.next();//str only contains "abc"
[...]
if(a[i] == ' ') //This condition is never met.
You can specify the delimiter like this :
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");

Related

charAt(0) gives java.lang.StringIndexOutOfBoundsException

String.charAt(0) is giving java.lang.StringIndexOutOfBoundsException even though the String is not empty
public class Mainc {
public static void main(String[] args) {
int T;
Scanner inp = new Scanner(System.in);
Scanner inp2 = new Scanner(System.in);
T = inp.nextInt();
for (int i = 0; i < T; i++) {
String u = "";
String l = "";
String s = inp2.nextLine();
while (s != null) {
char ch = s.charAt(0);
if (Character.isLowerCase(ch))
l += ch;
else
u += ch;
s = s.substring(1);
}
if (u.length() > l.length())
System.out.println(u);
else
System.out.println(l);
}
}
}
It's supposed to give an all uppercase String or all lowercase String depending on which is bigger or an all uppercase String if they were both equal length but it gives runtime error java.lang.StringIndexOutOfBoundsException
even though the String is not empty and the charAt() function is at index 0. Thanks in advance.
Your while loop loops through the string s, checks each character, adds that character to u or l, and then removes it from s. But what happens when all the characters are removed? s is now empty, but the while loop still executes, because s is not null (null and the empty string are different things!) This means that you would call s.charAt(0) when s is empty, which causes the crash.
To fix this, you can change the while loop conditions to "s is not empty" instead. You don't need to check if s is null because it comes from Scanner.nextLine, which shouldn't return null.
while (!s.isEmpty()) {
char ch = s.charAt(0);
if (Character.isLowerCase(ch))
l += ch;
else u += ch;
s = s.substring(1);
}
You can improve your code further by not removing the character from s in each iteration. Instead, use a for loop with an index to loop through the string. Also, you should use a StringBuilder when concatenating strings in a loop. Both of these will avoid creating unnecessary string objects.
StringBuilder u = new StringBuilder(); // notice the change to StringBuilder here
StringBuilder l = new StringBuilder();
String s = inp2.nextLine();
for (int j = 0 ; j < s.length() ; j ++) {
char ch = s.charAt(j);
if (Character.isLowerCase(ch))
l.append(ch);
else u.append(ch);
}
even your s value is ""(blank) its still going in while loop as its not null after finish all chars so use length while(s.length() > 0) should work.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int T;
Scanner inp=new Scanner(System.in);
Scanner inp2=new Scanner(System.in);
T=inp.nextInt();
for(int i=0;i<T;i++){
String u=""; String l="";
String s=inp2.nextLine();
while(s.length() > 0){
char ch=s.charAt(0);
if(Character.isLowerCase(ch))
l+=ch;
else u+=ch;
s = s.substring(1);}
if(u.length()>l.length())
System.out.println(u);
else System.out.println(l);
}
}
}

+= operator not working with string

I'm trying to produce a program that outputs the user's input in a form like this:
input: word
w
wo
wor
word
This incremental build-up doesn't seem to be working.
import java.util.*;
public class SpellMan {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in) ;
System.out.println("Give me a word > ");
String word = kb.nextLine();
for(int i = 0; i< word.length();i++){
String bword += ""+word.charAt(i);
System.out.println(bword);
}
}
}
You are declaring bword inside the loop, so in each iteration you attempt to concatenate the current character to an uninitialized String variable.
Try :
String bword = "";
for(int i = 0; i< word.length();i++) {
bword += word.charAt(i);
System.out.println(bword);
}
That said, using a StringBuilder would be more efficient (less objects will be created).
StringBuilder bword = new StringBuilder(word.length());
for(int i = 0; i< word.length();i++) {
bWord.append(word.charAt(i));
System.out.println(bword.toString());
}
Apart from other code problems, the main point concerning your question header is that you can not use += operator within the declaration, because bword is still null (It will not compile).
String bword = ""; //before the loop
bword += word.charAt(i);
System.out.println(bword);

write a code to find the number of words in a string using methods

I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT:
I have changed the code to
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
The getInputString method signature should be:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount method signature should be:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main method should look something like this:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
Use trim() and split() on 1-n whitespace chars:
private static int getWordCount(String s) {
return s.trim().split("\\s+").length;
}
The call to trim() is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
The parameter "\\s+" is necessary to count multiple spaces as a single word separator. \s is the regex for "whitespace". + is regex for "1 or more".
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
Happy learning!
You can do this by :
private static int getWordCount(String input) {
return input.split("\\s+").length;
}
Use String.split() method like :
String[] words = s.split("\\s+");
int wordCount = words.length;
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main() method that does this for you, for example:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
Based on your code i think this is what you're trying to do:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
I've moved the code you were 'playing' with into the right method (getWordCount).
Corrected the loop you were trying to use (I think you have for and while loops confused)
Fixed your check for the space character (' ' not " ")
There is a bug in this code which you'll need to work out how to fix:
getWordCount("How are you"); will return 2 when it should be 3
getWordCount(""); will return 0
getWordCount("Hello"); will return 0 when it should be 1
Good luck!
Better use simple function of spilt() with arguments as space
int n= str.split(" ").length;
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}

Removing white spaces from string using loops

Hi guys I'm trying to remove white spaces using loops specifically. Heres what I've come up with so far
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
String input = "";
char noSpace = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { //search from right to left
for (int j = input.length(); j != -1; j--) { //search from left to right
if (input.charAt(i) == noSpace) { //if there is a space move position of i and j
i++;
j--;
}
}
System.out.println(input);
I am still quite new to java, any suggestions would be great thanks!
Try this one:
public class RemoveWhiteSpace {
public static void main(String[] args) {
String str = "Hello World... Hai... How are you? .";
for(Character c : str.toCharArray()) {
if(!Character.isWhitespace(c)) // Check if not white space print the char
System.out.print(c);
}
}
}
Why you do not use regular expressions? replaceAll("\\s","") removes all whitespaces. Also you can remove other non visible symbols, such as \tab etc.
Look at docs.oracle.com for more info
And a combination of themes...
StringBuilder result = new StringBuilder(64);
String str = "sample test";
for (Character c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
result.append(c);
}
}
System.out.println(result.toString()); // toString is not required, but I've had to many people assume that StringBuilder is a String
System.out.println(str.replace(" ", ""));
System.out.println("Double spaced".replace(" ", ""));
Basically, nothing new, just runnable examples of what every body else has spoken about...
import java.util.Scanner;
public class Iterations{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = kb.nextLine();
String temp = "";
for (int i = 0; i < s.length(); i++){ //This loops separates the string into each character
String c = s.substring(i, i+1);
if (c.equals(" ")){
System.out.print(c.trim()); //If the individual character is space then remove it with trim()
} else {
temp = temp + c; //Adds the string up into single sentence
}
}
System.out.println(temp); //Print it to have a nice line of string
}
}
I am also new to java and happen to do problems that remove spaces with only some methods and loops. Thats my solution, feel free to try it out.
public class sample {
public static void main(String[] args) {
String input = "sample test";
char noSpace = ' ';
System.out.println("String original:"+input);
for (int i = 0; i < input.length(); i++) { //search from right to left
if (input.charAt(i) != noSpace) { //if there is a space move position of i and j
System.out.print(input.charAt(i));
}
}
}
}
You've actually gone too far by keeping two loops you could do it in one only:
public static void main(String[] args) {
String input = "";
char space = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { // search from right to left char by char
if (input.charAt(i)!= space) { // if the char is not space print it.
System.out.print(input.charAt(i));
}
}
}

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

Categories

Resources