This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
public void display()
{
super.display();
String str = super.getChoices();
System.out.println(str);
while(!str.equals(""))
{
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
}
}
I have a String str containing "Apple Banana Orange". I want to system out print these fruits separately because they are each a choice to a question stored in a single variable. How can I do this? The code above is my failed attempt because the substring doesn't update the str variable rather creates a new string. I can't use a loop and I can't make it dynamic and thus not use it.
You need to change str as well:-
while(!str.equals("") ) {
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
str = str.substring(a); // Remove the bit of str that we've processed.
}
(Untested, but you get the idea). You obviously also need to check if str actually contains a space and drop out.
If i understand you correctly, you should try to use StringTokenizer
StringTokenizer st=new StringTokenizer("Apple Banana Orange");
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}
Related
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I already have a string let's say
String abc = "Stack";
Now, I want to modify this string using scanner class only ! So, user should to able to see existing string on console and then he can edit that string.
I tried this, but then it just replaces the existing string.
System.out.println("Edit the below string");
System.out.println(abc);
abc = scanner.nextLine();
How would I achieve it ?
Well the issue is you shouldn't with just a String. Your problem is the reason StringBuffer was created. Ideal solution:
StringBuffer buffer = new StringBuffer("Stack");
while (scanner.hasNextLine()){
buffer.append(scanner.nextLine());
System.out.println(buffer.toString());
}
String abc = buffer.toString(); //if you really need to save it to variable 'abc' for some reason.
Here is a terrible example if you hate your computer and can only user a String.
String abc = "Stack";
while (scanner.hasNextLine()){
abc += scanner.nextLine();
System.out.println(abc);
}
The above is a terrible solution for memory reason.
I hope this helps
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am writing a Java program to practice my programming skill. The program is supposed to read input from a file, split it using space, and then print it out.
import java.io.*;
import java.util.*;
public class SumsInLoopTester {
public static void main(String[] args) {
try
{
File f = new File("SumsInLoop.txt");
Scanner sc = new Scanner(f);
int n = sc.nextInt();
int i = 0;
int sum[] = new int[n]; // I will use this later
while(sc.hasNextLine())
{
String input = sc.nextLine();
String splits[] = input.split("\\s+");
System.out.println(splits[0]);
System.out.println(splits[1] + "\n");
}
} catch(FileNotFoundException e) {
System.out.println(e);
}
}
}
Here is what's inside the input file:
SumsInLoop.txt
The output I expect to see is:
761892
144858
920553
631146
.
.
.
.
.
.
.
.
But instead, I got ArrayIndexOutofBoundsException exception. I tried to add space after each number on the second column and it worked. But I'm just curious why it wouldn't work without adding spaces. I spent so much time trying to figure this out, but no clue. I know that I don't have to split the string before I output it. Just want to have a little practice with split() method and get to know it better.
If you expect to see this:
761892 144858
920553 631146
simply use like this ,
while (sc.hasNextLine()) {
String input = sc.nextLine();
System.out.println(input);
}
there is no use of doing System.out.println(splits[1] + "\n"); since splits[1] don't have any value
First of all, you should not expect to see
761892 144858
920553 631146
Because you have already split by whitespace, you wont find whitespace in splits
Your problem is most likely caused by some lines in file has no whitespace. Then indexing splits[1] would throw ArrayIndexOutofBoundsException because in that case splits only has one element
Edit: you can make a conditional statemetn before printing
replace
System.out.println(splits[1] + "\n");
with
if (splits.length > 1) {
System.out.println(splits[1] + "\n");
}
I am trying to split two lines of strings inputted into the scanner as one big string, back into two separate strings (as shown with my below example and expected output).
Pseudo Code-ish Code
Scanner s = new Scanner("Fred: 18Bob D: 20").useDelimiter(":") //delimiter is probably pointless here
List<String> list = new ArrayList<>();
while (s.hasNext()) {
String str = "";
if (//check if next token is str) {
str = str + s.next();
}
if (//check if next token is :) {
//before the : will always be a name of arbitary token length (such as Fred,
//and Bob D), I also need to split "name: int" to "name : int" to achieve this
str = str + ": " + s.next();
}
if (//check if next token is alphanumeral) {
//split the alphanumeral then add the int to str then the character
str = str + s.next() + "\n" + s.next() //of course this won't work
//since s.next(will go onto the letter 'D')
}
else {
//more code if needed otherwise make the above if statement an else
}
list.add(str);
}
System.out.println(list);
Expected Output
Fred: 18
Bob D: 20
I just can't figure out how I can achieve this. If any pointers towards achieving this can be given, I would be more than thankful.
Also, a quick question. What's the difference between \n and line.separator and when should I use each one? From the simple examples I've seen in my class codes, line.separator has been used to separate items in a List<String> so that's the only experience I have with that.
You can try below snippet for your purpose :
List<String> list = new ArrayList<String>();
String str="";
while(s.hasNext()){
if(s.hasNextInt()){
str+=s.nextInt()+" ";
}
else {
String tmpData = s.next();
String pattern = ".*?(\\d+).*";
if(tmpData.matches(pattern)){
String firstNumber = tmpData.replaceFirst(".*?(\\d+).*", "$1");
str+=firstNumber;
list.add(str);
str="";
str+=tmpData.replace(firstNumber, "")+" ";
}else{
str+=tmpData;
}
}
}
list.add(str);
System.out.println(list);
This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
How to upper case every first letter of word in a string? [duplicate]
(16 answers)
Closed 8 years ago.
Hey guys so im new to java and im trying to write a program that declares two strings
First && Last name ( both under case )
And i need to use the .uppercase to convert the first letter in both the first name and last name from lower case to uppercase.
Example convert jon to Jon
This is what i have so far
I really dont understand how i make the first letter uppercase.
/////
public class firstProgram {
public static void main(String args[])
{
//NAME GOES HERE. DECLARED 2 STRINGS
String first = "firstname";
String last = "lastname";
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
}
}
You can do something like -
String first = "firstname";
String last = "lastname";
first = String.valueOf(first.charAt(0)).toUpperCase() + first.substring(1);
last = String.valueOf(last.charAt(0)).toUpperCase() + last.substring(1);
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
You can check documentation for toUpperCase().
If you only want to capitalize the first letter of a string named first and leave the rest alone:
first = first.substring(0, 1).toUpperCase() + first.substring(1);
Now first will have what you want.
Do like this for last
You can do this by employing the String class subString methods.
String input = "first name";
String out = input.substring(0, 1).toUpperCase() + input.substring(1);
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
or in class
class FirstProgram {
public static void main(String[] args) {
String firstName = "arun";
String lastName = "kumar";
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
System.out.println(firstName+ " "+lastName);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a String with some text, f.e.
"Thisisalongwordtest and I want tocutthelongword in pieces"
Now I want to cut the to longs word in 2 pieces with a blank. The word should be cut if it's longer than 10 characters.
The result should be:
"Thisisalon gwordtest and I want tocutthelo ngword in pieces"
How can I achieve this efficiently?
are you looking for this? or I misunderstood the question?
String newString = oldStr.replaceAll("\\w{10}","$0 "))
with your example, the newString is:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Edit for Pshemo's good comment
to avoid to add space after words with exact 10 chars:
str.replaceAll("\\w{10}(?=\\w)","$0 "));
.replaceAll("(\\w{10})(?=\\w)", "$1 ")
Tested with:
test("abcde fghij klmno pqrst");
test("abcdefghijklmnopqrst");
test("abcdefghijklmnopqrstuv");
test("abcdefghij klmnopqrstuv");
test("abcdefghij klmnopqrst uv");
separate text into words. (by space)
cut long words and replace source word with new words
assemble text again
Note, that this approach will kill multiple-spaces.
(?=\w{10,}\s)(\w{10})
Should be replaced by
"\1 "
you can use replace function.
If it has number or special characters
(?=\S{10,}\s)(\S{10})
can be used.
This is the code i wrote check it once.....
public class TakingInput {
public static void main(String[] args) {
String s="Thisisalongwordtest and I want tocutthelongword in pieces";
StringBuffer sb;
String arr[]=s.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].length()>10){
sb=new StringBuffer(arr[i]);
sb.insert(10," ");
arr[i]=new String(sb);
}
}
for(String ss: arr){
System.out.println(ss);//o/p: "Thisisalon gwordtest and I want tocutthelo ngword in pieces"
}
}
}
This code will do exactly what you want.
First create a method that splits a String if its longer than 10 chars:
String splitIfLong(String s){
if(s.length() < 11) return s + " ";
else{
String result = "";
String temp = "";
for(int i = 0; i < s.length(); i++){
temp += s.charAt(i);
if(i == 9)
temp += " ";
result += temp;
temp = "";
}
return result + " ";
}
}
Then use Scanner to read every word in the sentence seperated by a white space" ":
String s = "Thisisalongwordtest and I want tocutthelongword in pieces";
String afterSplit = "";
Scanner in = new Scanner(s);
Then call the splitIfLong() method for every word in the sentence. And add what the method returns to a new String:
while(in.hasNext())
afterSplit += splitIfLong(in.next());
Now you can use the new String as you wish. If you call:
System.out.println(afterSplit);
it will print:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Hope this helps