Get complete word from string in lines , java? [duplicate] - java

This question already has answers here:
Wrap the string after a number of characters word-wise in Java
(6 answers)
Closed 8 years ago.
Let us say I have a long string
String s1="This is my world. This has to be broken."
I am breaking the above string at a fixed interval of string length let's say when it's 10.
So the output I get after breaking is
This is my
world. Thi
s has to b
e broken.
Where as I want that the string should contain complete words and not broken words.
Just like this I want the output to be
This is my
world.
This has
to be
broken.
How can I achieve the above output.

Try this:
String line = "element1 element2 element3";
String [] separatedList = line.split("\\s+");
for (String stringSeparated : separatedList) {
System.out.println(stringSeparated);
}

I don't exactly understand the logic of the program, but you can use String.indexOf(' ') or something like that to know where exactly are the spaces of your string. check here http://www.tutorialspoint.com/java/java_string_indexof.htm and read the documentation http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)

Something along these lines?
int limit = 10;
// Tokenize words
String s1="This is my world. This has to be broken.";
final String[] words = s1.split( " " );
// Apply word-wrapping
final StringBuilder sb = new StringBuilder();
for( String word : words ) {
if( sb.length() + word.length() > limit ) {
// Next word wraps
System.out.println( sb );
sb.setLength( 0 );
}
else {
// Otherwise add to current line
if( sb.length() > 0 ) sb.append( ' ' );
}
sb.append( word );
}
// Handle final line
System.out.println( sb );

Related

How to remove the last comma from the output in java? [duplicate]

This question already has answers here:
The simplest way to comma-delimit a list?
(30 answers)
Closed 2 years ago.
System.out.print(i+",");
I am trying to print a list of numbers using for loop and I am using the above line. But I get the output 1,2,3,. I need 1,2,3.
How can I do it?
Many ways.
Use a StringBuilder to make your string, then after the loop, if it is not empty, lop off the last character (sb.setLength(sb.length() - 1)).
Use a boolean to track if this is the first time through the loop. If yes, just print the number. If not, print a comma, then the number. Set the boolean to false after.
Use string joining:
List<String> items = List.of("Hello", "World!");
System.out.println(String.join(", ", items));
Here's what I would do... use a StringBuilder and append to it inside of the loop like this.
Once the loop is finished, your output string will be ready and you can just remove the last character (which will be the comma)
StringBuilder sb = new StringBuilder();
for () {
sb.append(i+",");
}
// remove last comma
sb.setLength(sb.length() - 1);
System.out.println(sb.toString);
Well there's standard library's method for it:
String.join(", ", s);
var buffer = new java.util.StringJoiner( "," );
for( var i = 1; i < endCriterion; ++i )
{
buffer.add( Integer.toString( i );
}
System.out.println( buffer.toString() );
For endCriterion == 3 this will print
1,2,3
to the console.
'java.util.StringJoiner' was added to the Java standard library with Java 8.

How to explode a string on a hyphen in Java?

I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.

how to print first Characters from multiple string in java? [duplicate]

This question already has answers here:
Get string character by index
(13 answers)
Closed 8 years ago.
i want to print first character from multiple word , this word coming from api , like
DisplayName: arwa othman .
i want to print the letter (a) and (o).
can anyone to help me please ??
Try this
public String getFirstWords(String original){
String firstWord= "";
String[] split = original.split(" ");
for(String value : split){
firstWord+= value.substring(0,1);
}
return firstWord;
}
And use this as
String Result = getFirstWords("arwa othman");
Edit
Using Regex
String name = "arwa othman";
String firstWord= "";
for(String s : name.split("\\s+")){
firstWord += s.charAt(0);
}
String Result = firstWord;
You can use the the Apache Commons Langs library and use the initials() method , you can get more information from here http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#initials(java.lang.String)
I am quoting a sample code snippet that might be useful :
WordUtils.initials(null) = null
WordUtils.initials("") = ""
WordUtils.initials("Ben John Lee") = "BJL"
WordUtils.initials("Ben J.Lee") = "BJ"
This may work for you:
String[] splitArray = displayName.split("\\s+");
char[] initials = new char[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
initials[i] = splitArray[i].charAt(0);
}
This will give you a char array. If you want a String array use String.valueOf(char)

Reversing the order of a string

So I'm still shaky on how basic java works, and here is a method I wrote but don't fully understand how it works anyone care to explain?
It's supposed to take a value of s in and return it in its reverse order.
Edit: Mainly the for loop is what is confusing me.
So say I input "12345" I would want my output to be "54321"
Public string reverse(String s){
String r = "";
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r;
}
return r;
}
We do a for loop to the last index of String a , add tha carater of index i to the String s , add here is a concatenation :
Example
String z="hello";
String x="world";
==> x+z="world hello" #different to z+x ="hello world"
for your case :
String s="";
String a="1234";
s=a.charAt(0)+s ==> s= "1" + "" = "1" ( + : concatenation )
s=a.charAt(1)+s ==> s='2'+"1" = "21" ( + : concatenation )
s=a.charAt(2)+s ==> s='3'+"21" = "321" ( + : concatenation )
s=a.charAt(3)+s ==> s='3'+"321" = "4321" ( + : concatenation )
etc..
public String reverse(String s){
String r = ""; //this is the ouput , initialized to " "
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r; //add to String r , the caracter of index i
}
return r;
}
What this code does is the following
Create a new variable r="";
then looping for the string in input lenght it adds at the beginning of r the current character of the loop.
i=0) r="1"
i=1) r="21"
i=2) r="321"
i=3) r="4321"
i=4) r="54321"
When you enter the loop you are having empty string in r.
Now r=""
In 1st iteration, you are taking first character (i=0) and appending r to it.
r = "1" + "";
Now r=1
In 2nd iteration, you are taking second character (i=1) and appending r to it
r = "2" + "1";
Now r=21
You can trace execution on a paper like this, then you will easily understand what is happening.
What the method is doing is taking the each character from the string s and putting it at the front of the new string r. Renaming the variables may help illustrate this.
public String reverse(String s){
String alreadyReversed = "";
for(int i=0; i<s.length(); i++){
//perform the following until count i is as long as string s
char thisCharacterInTheString = s.charAt(i); // for i==0 returns first
// character in passed String
alreadyReversed = thisCharacterInTheString + alreadyReversed;
}
return alreadyReversed;
}
So in the first iteration of the for loop alreadyReversed equals 1 + itself (an empty string).
In the second iteration alreadyReversed equals 2 + itself (1).
Then 3 + itself (21).
Then 4 + 321.
Then 5 + 4321.
GO back to your problem statement (take an input string and produce an output string in reverse order). Then consider how you would do this (not how to write Java code to do this).
You would probably come up with two alternatives:
Starting at the back of the input string, get one character at a time and form a new string (thus reversing its order).
Starting at the front of the string, get a character. Then for each next character, put it in front of all the characters you have created so far.
Your pseudo code results might be like the following
Option 1
let l = the length of the input string
set the output string to ""
while l > 0
add the "lth" character of the input string to the output string
subtract 1 from l
Option 2 left as an exercise for the questioner.
Then you would consider how to write Java to handle your algorithm. You will find that there are several ways to get the "lth" character of a string. First, in Java a string of length l has characters in position 0 through l-1. You can use string.charAt(loc) or string.substring(loc,loc+1) to get the character at position loc

Java - dynamically pad left with printf

I'm learning Java and have spent way too much time on this stupid little problem. I'm trying to dynamically pad the left side of my string outputs with spaces, so all values displayed will be padded left. The problem is, I don't know the length of the values until a user enters them.
Here's an example of what I'm trying to do. nLongestString is the length of the longest string I'm displaying, and strValue is the value of the string itself. This doesn't work dynamically at all. If I hardcode a value for nLongestString it works, but I can't do that since I don't always know how long the strings will be.
System.out.printf("%"+nLongestString+"s", strValue + ": ");
Output should look like:
thisisalongstring:
longstring:
short:
I'm not seeing your problem, the following works fine for me. (Java 7)
Edit: Have you checked the value of nLongestString? I'm guessing it doesn't get set to what you think it does.
String[] arr = { "foo", "bar", "foobar" };
int max = 0;
for( String s : arr ) {
if( s.length() > max ) {
max = s.length();
}
}
for( String s : arr ) {
System.out.printf( ">%" + max + "s<%n", s );
}
Random random = new Random( System.currentTimeMillis() );
// just to settle the question of whether it works when
// Java can't know ahead of time what the value will be
max = random.nextInt( 10 ) + 6;
for( String s : arr ) {
System.out.printf( ">%" + max + "s<%n", s );
}
}
Output:
> foo<
> bar<
>foobar<
// the following varies, of course
> foo<
> bar<
> foobar<
If you already have your data then you just need to find max length of your words and after that print them. Here is code sample
// lets say you have your data in List of strings
List<String> words = new ArrayList<>();
words.add("thisisalongstring");
words.add("longstring");
words.add("short");
// lets find max length
int nLongestString = -1;
for (String s : words)
if (s.length() > nLongestString)
nLongestString = s.length();
String format = "%"+nLongestString+"s:\n";// notice that I added `:` in format so
// you don't have to concatenate it in
// printf argument
//now lets print your data
for (String s:words)
System.out.printf(format,s);
Output:
thisisalongstring:
longstring:
short:

Categories