Print String words reverse - edge cases - java

I try to create a function that changes the String from StackOverflow is the best. to best. the is StackOverflow.
I wrote the following function, but can't seem to fix the spaces in the result string. For some reason, I receive best.the is Stackoverflow. There is no space between best. & the, and there is an extra space after StackOverflow.
I could add a variable that represents space and use if's in the edge cases, but I believe that there is a better way to do so.
Could anyone help me figure this out?
public static void main(String[] args) {
String str = "Stackoverflow is the best.";
String result = change(str);
System.out.println(result);
}
private static String change(String str) {
String result = "";
int i1 = str.length()-1;
int i2 = str.length();
for (i1 = str.length(); i1 >= 0; i1--) {
if (i1 ==0 || str.charAt(i1-1) == ' ') {
result = result.concat(str.substring(i1, i2));
i2 = i1;
}
}
return result;
}

One way i could think of without using if's is :
String line = "Stackoverflow is the best.";
String delimeter = " ";
final String[] words = line.split(delimeter);
String reversedLine = "";
for(int i = words.length - 1; i >= 0; i--) {
reversedLine += words[i] + delimeter;
}
// remove the delimeter present at last of line
reversedLine = reversedLine.substring(0, reversedLine.length() - 1);
System.out.println(reversedLine);

To generate the output as you have mentioned, I would approach a problem in this way:
class Solution {
public static void main(String[] args) {
String str = "StackOverflow is the best.";
String[] arr = str.split(" ");
System.out.print(arr[arr.length-1]);
for(int i = arr.length - 2; i >= 0; i--){
System.out.print(" "+arr[i]);
}
}
}

The only reason to your problem is that you haven't added the space after the '.'
Try using String str = "Stackoverflow is the best. ";
Hope it helped... :)

Related

How to insert a char before each char in a string, but not before 'space' in Java?

This is what I got. It works for now, but if I type, for example, "I like bananas", I get 'pIp ppipkpep pbpapnpapnpaps', while I'm aiming to get 'pI pLpipkpe pbpapnpapnpaps.
Every solution I tried came down to using an 'if statement', trying to check if the character at said position in the original 'encText'is equal to ' ', and if so, making it equal to ' ' as well in the newText array before checking if the position required an 'p' or the char from the original array.. However, everytime I tried that, I'd get an array out of bounds exception.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j = 1;
for (int i = 0; i < (k*2); i++) {
if (i%2 == 0) {
newText[i] = 'p';
} else {
newText[i] = charsEncText[i-j];
j++;
}
}
System.out.println(newText);
}
A simpler solution is to use replaceAll with a positive lookahead.
String str = "I like bananas";
String res = str.replaceAll("(?=[^ ])", "p");
System.out.println(res); // "pI plpipkpe pbpapnpapnpaps"
Demo
You can try this way.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j=0;
for(int i=0;i<k;i++)
{
if(charsEncText[i]==' ')
{
newText[j]=charsEncText[i];
j++;
}
else{
newText[j]='p';
newText[j+1]=charsEncText[i];
j=j+2;
}
}
System.out.println(newText);
}
Assuming one does not need a char[], I would just concatenate to a String. Something like:
public static String pEncrypt(String org)
{
String ret = "";
for (int i = 0; i < org.length(); ++i) {
char ch = org.charAt(i);
if (ch != ' ') {
ret += "p" + ch;
}
else {
ret += ' ';
}
}
return ret;
}
Also, to make things a bit easier, it is generally a good idea to separate the I/O (i.e., the Scanner and the println) from the processing. That way, one can write test cases rather than attempting to keep inputting the information.
Sample Output:
helloworld ==> phpeplplpopwpoprplpd
I like bananas ==> pI plpipkpe pbpapnpapnpaps

How to split a string after 2nd occurrence of dot(.) in java

I have a string which looks something like this(the most basic form):
String str = "1.0.0.190"
The str can be something like this as well:
1.11.0.12 or 2.111.1.190 or 1.0.0.0
I want to split the string at the 2nd occurrence of the dot(.). How can I achieve that ?
Output:
String str = "1.0.0.190"
String output = "1.0"
I'd fit the answer to OP's level, so I wouldn't recommend split or regexps to him...
If you need substring to second dot, simply find second dot and cut the string to that position...
public class DotSubstring {
public static void main(String[] args) {
String s = "1.2.3.4";
int secondDotPosition = findSecondDotPosition(s);
if (secondDotPosition > 0) {
System.out.println(s.substring(0, secondDotPosition));
} else {
System.out.printf("ERROR: there is not a 2nd dot in '%s'%n", s);
}
}
private static int findSecondDotPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == '.') --dotsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
}
The problem with split for beginner is, that is accepts regexp, that's why it is escaped in Joop Eggen's answe like this str.split("\\.").
And yes, that can be achieved in one line as user3458271 wrote in a comment same as xyz later in answer, just error checking would be more difficult (for example if there are no 2 dots...).
In one line with substring and indexOf:
String output = str.substring(0,str.indexOf(".",str.indexOf(".")+1));
public static void main(String[] args) {
String input = "2.111.1.190";
String[] out = input.split("\\.");
String output1 = out[0]+"."+out[1];
System.out.println(output1);
String output2 = "";
for(int x=2; x < out.length; x++)
output2 += out[x] +".";
System.out.println(output2);
}
For the other fields too:
String[] halfs = str.split("\\.");
String[] fulls = new String[halfs.length / 2];
for (int i = 0; i < fulls.length; ++i) {
fulls[i] = halfs[2*i] + "." + halfs[2*i + 1];
}
return fulls[0];
The same technique reduced for the first field:
String[] halfs = str.split("\\.", 3);
return halfs[0] + "." + halfs[1];
Simply:
return str.replaceAll("^([^.]*\\.[^.]*)\\..*$", "$1");

Can anybody help me to correct the following code?

Please help me to identify my mistakes in this code. I am new to Java. Excuse me if I have done any mistake. This is one of codingbat java questions. I am getting Timed Out error message for some inputs like "xxxyakyyyakzzz". For some inputs like "yakpak" and "pakyak" this code is working fine.
Question:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
public String stringYak(String str) {
String result = "";
int yakIndex = str.indexOf("yak");
if (yakIndex == -1)
return str; //there is no yak
//there is at least one yak
//if there are yaks store their indexes in the arraylist
ArrayList<Integer> yakArray = new ArrayList<Integer>();
int length = str.length();
yakIndex = 0;
while (yakIndex < length - 3) {
yakIndex = str.indexOf("yak", yakIndex);
yakArray.add(yakIndex);
yakIndex += 3;
}//all the yak indexes are stored in the arraylist
//iterate through the arraylist. skip the yaks and get non-yak substrings
for(int i = 0; i < length; i++) {
if (yakArray.contains(i))
i = i + 2;
else
result = result + str.charAt(i);
}
return result;
}
Shouldn't you be looking for any three character sequence starting with a 'y' and ending with a 'k'? Like so?
public static String stringYak(String str) {
char[] chars = (str != null) ? str.toCharArray()
: new char[] {};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
// then it's unlucky...
i += 2;
continue; //skip the statement sb.append
} //do not append any pattern like y1k or yak etc
sb.append(chars[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
// The result will be 1234.
}
It looks like your programming assignment. You need to use regular expressions.
Look at http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex for more information.
Remember, that you can not use contains. Your code maybe something like
result = str.removeall("y\wk")
you can try this
public static String stringYak(String str) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='y'){
str=str.replace("yak", "");
}
}
return str;
}

Removing contiguous spaces in a String without trim() and replaceAll()

I have to remove leading and trailing spaces from the given string as well as combine the contiguous spaces. For example,
String str = " this is a string containing numerous whitespaces ";
and I need to return it as:
"this is a string containing numerous whitespaces";
But the problem is I can't use String#trim(). (This is a homework and I'm not allowed to use such methods.) I'm currently trying it by accessing each character one-by-one but quite unsuccessful.
I need an optimized code for this. Could anybody help? I need it to be done by today :(
EDIT: Answer posted before we were told we couldn't use replaceAll. I'm leaving it here on the grounds that it may well be useful to other readers, even if it's not useful to the OP.
I need an optimized code for this.
Do you really need it to be opimtized? Have you identified this as a bottleneck?
This should do it:
str = str.replaceAll("\\s+", " ");
That's a regular expression to say "replace any contintiguous whitespace with a single space". It may not be the fastest possible, but I'd benchmark it before trying anything else.
Note that this will replace all whitespace with spaces - so if you have tabs or other whitespace characters, they will be replaced with spaces too.
I'm not permitted to use these methods. I've to do this with loops
and all.
So i wrote for you some little snipet of code if you can't use faster and more efficient way:
String str = " this is a string containing numerous whitespaces ";
StringBuffer buff = new StringBuffer();
String correctedString = "";
boolean space = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
if (!space && i > 0) {
buff.append(c);
}
space = true;
}
else {
buff.append(c);
space = false;
}
}
String temp = buff.toString();
if (temp.charAt(temp.length() - 1) == ' ') {
correctedString = temp.substring(0, buff.toString().length() - 1);
System.out.println(correctedString);
}
System.out.println(buff.toString())
Note:
But this is "harcoded" and only for "learning".
More efficient way is for sure use approaches pointed out by #JonSkeet and #BrunoReis
What about str = str.replaceAll(" +", " ").trim();?
If you don't want to use trim() (and I really don't see a reason not to), replace it with:
str = str.replaceAll(" +", " ").replaceAll("^ ", "").replaceAll(" $", "");`
Remove White Spaces without Using any inbuilt library Function
this is just a simple example with fixed array size.
public class RemWhite{
public static void main(String args[]){
String s1=" world qwer ";
int count=0;
char q[]=new char[9];
char ch[]=s1.toCharArray();
System.out.println(ch);
for(int i=0;i<=ch.length-1;i++)
{
int j=ch[i];
if(j==32)
{
continue;
}
else
q[count]=ch[i];
count++;
}
System.out.println(q);
}}
To remove single or re-occurrence of space.
public class RemoveSpace {
public static void main(String[] args) {
char space = ' ';
int ascii = (int) space;
String str = " this is a string containing numerous whitespaces ";
char c[] = str.toCharArray();
for (int i = 0; i < c.length - 1; i++) {
if (c[i] == ascii) {
continue;
} else {
System.out.print(c[i]);
}
}
}
}
If you don't want to use any inbuilt methods here's what you refer
private static String trim(String s)
{
String s1="";boolean nonspace=false;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=' ' || nonspace)
{
s1 = s1+s.charAt(i);
nonspace = true;
}
}
nonspace = false;
s="";
for(int i=s1.length()-1;i>=0;i--)
{
if(s1.charAt(i)!=' ' || nonspace)
{
s = s1.charAt(i)+s;
nonspace = true;
}
}
return s;
}
package removespace;
import java.util.Scanner;
public class RemoveSpace {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the string");
String str= scan.nextLine();
String str2=" ";
char []arr=str.toCharArray();
int i=0;
while(i<=arr.length-1)
{
if(arr[i]==' ')
{
i++;
}
else
{
str2= str2+arr[i];
i++;
}
}
System.out.println(str2);
}
}
This code is used for removing the white spaces and re-occurrence of alphabets in the given string,without using trim(). We accept a string from user. We separate it in characters by using charAt() then we compare each character with null(' '). If null is found we skip it and display that character in the else part. For skipping the null we increment the index i by 1.
try this code to get the solution of your problem.
String name = " abc ";
System.out.println(name);
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == ' ') {
i = 2 + i - 2;
} else {
System.out.print(name.charAt(i));
}
}

How to reverse a string

I need to reverse the string of a user's input.
I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn't working.
For example, user inputs abc I just take the string and print out cba
new StringBuilder(str).reverse().toString()
java.util.Collections.reverseOrder is for sorting in reverse of normal order.
I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:
StringUtils.reverse("Hello World!");
yields: !dlroW olleH
StringUtils.reverseDelimited("Hello World!", ' ');
yields: World! Hello
If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?".
Understand the internals and play some!!
public static void main(String[] args) {
String str = "abcasz";
char[] orgArr = str.toCharArray();
char[] revArr = new char[orgArr.length];
for (int i = 0; i < orgArr.length;i++) {
revArr[i] = orgArr[orgArr.length - 1 - i];
}
String revStr = new String(revArr);
System.out.println(revStr);
There is an interesting method to do it so too.
String input = "abc";
//Here, input is String to reverse
int b = input.length();
String reverse = ""; // Declaring reverse String variable
while(b!=0){
//Loop for switching between the characters of the String input
reverse += (input.charAt(b-1));
b--;
}
System.out.println(reverse);
public String reverseString(final String input_String)
{
char temp;
char[] chars = input_String.toCharArray();
int N = chars.length;
for (int i = 0 ; i < (N / 2) ; i++)
{
temp = chars[i];
chars[i] = chars[N - 1 - i];
chars[N - 1 - i] = temp;
}
return new String(chars);
}
Run :
Pandora
arodnaP
Without going through the char sequence, easiest way:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward = backward + post.substring(i, i + 1);
}
return backward;
}

Categories