How to remove whitespace from the start and end of a String without using the trim() method?
here is my code
public class StringTest {
public static void main(String[] args) {
String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport ";
//System.out.println(line);
int endIndex = line.indexOf("|");
String Country = line.substring(0, endIndex);
line = line.substring(endIndex + 1);
int endIndexCountry = line.indexOf("|");
String Code = line.substring(0, endIndexCountry);
line = line.substring(endIndexCountry + 1);
int endIndexCode = line.indexOf("|");
String City = line.substring(0, endIndexCode);
line = line.substring(endIndexCode + 1);
int endIndexCity = line.indexOf("|");
String State = line.substring(0, endIndexCity);
line = line.substring(endIndexCity + 1);
System.out.print("Code:" + Code + "____");
System.out.print("Country:" + Country + "____");
System.out.print("State:" + State + "____");
System.out.print("City:" + City + "____");
System.out.println("Airport:" + line+ "____");
}
}
and my output looks like this
Code: WNP____Country: Philippines____State:Camarines Sur____City:Naga ____Airport:Naga Airport ____
I need to look like this(without whitespaces)
Code:WNP____Country:Philippines____State:Camarines Sur____City:Naga____Airport:Naga Airport____
How to remove whitespace from the start and end of a String without
using the trim() method?
You can do it using a combination of regex patterns and String::replaceAll.
public class Main {
public static void main(String[] args) {
String str = " Hello ";
System.out.println("Before: " + str + "World!");
str = str.replaceAll("^[ \\t]+", "").replaceAll("[ \\t]+$", "");
System.out.println("After: " + str + "World!");
}
}
Output:
Before: Hello World!
After: HelloWorld!
Related
I have no idea why my output is not coming out correct. For example, if the input is "Running is fun" then the output should read "Is running fun". However, the output I am getting is "Iunning".
import java.util.Scanner;
public class Problem1 {
public static void main( String [] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space = sentence.indexOf(" ");
String firstWord = sentence.substring(0, space + 1);
String removedWord = sentence.replaceFirst(firstWord, "");
String newSentence = removedWord.substring(0,1).toUpperCase() +
firstWord.substring(1).toLowerCase();
System.out.println("");
System.out.println( newSentence );
}
}
removedWord.substring(0,1).toUpperCase() this line adds the capitalized first letter of the second word in the sentence. (I)
firstWord.substring(1).toLowerCase(); adds every letter of the first word to the end of the sentence. (unning)
Thus this creates the output of Iunning. You need to add the rest of removedWord to the String, as well as a space, and the first letter of firstWord, as a lower case letter at the space in removedWord. You can do this more by using indexOf to find the space, and then using substring() to add on firstWord.toLowerCase() right after the index of the space:
removedWord = removedWord.substring(0, removedWord.indexOf(" ")) + " " +
firstWord.toLowerCase() +
removedWord.substring(removedWord.indexOf(" ") + 1,
removedWord.length());
String newSentence = removedWord.substring(0,1).toUpperCase() +
removedWord.substring(1, removedWord.length());
Output:
Is running fun
Your problem is that
firstWord.substring(1).toLowerCase()
Is not working as you expect it to work.
Given firstWord is “Running“ as in your example, then
”Running“.substring(1)
Returns ”unning“
”unning“.toLowerCase()
Obviously returns ”unning“
The problem is at String newSentence. You not make the right combination of firstWord and removedWord.
This is how should be for your case:
String newSentence = removedWord.substring(0, 1).toUpperCase() // I
+ removedWord.substring(1,2) + " " // s
+ firstWord.toLowerCase().trim() + " " // running
+ removedWord.substring(2).trim(); // fun
EDIT(add new solution. credits #andy):
String[] words = sentence.split(" ");
words[1] = words[1].substring(0, 1).toUpperCase() + words[1].substring(1);
String newSentence = words[1] + " "
+ words[0].toLowerCase() + " "
+ words[2].toLowerCase();
This works properly:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space1 = sentence.indexOf(' ');
int space2 = sentence.indexOf(' ', space1 + 1);
if (space1 != -1 && space2 != -1) {
String firstWord = sentence.substring(0, space1 + 1);
String secondWord = sentence.substring(space1 + 1, space2 + 1);
StringBuilder newSentence = new StringBuilder(sentence);
newSentence.replace(0, secondWord.length(), secondWord);
newSentence.replace(secondWord.length(), secondWord.length()+ firstWord.length(), firstWord);
newSentence.setCharAt(0, Character.toUpperCase(newSentence.charAt(0)));
newSentence.setCharAt(secondWord.length(), Character.toLowerCase(newSentence.charAt(secondWord.length())));
System.out.println(newSentence);
}
}
I have a string which looks like below.
{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}
I need to extract the details/values from the above and add them to a list. By details I mean:
["firstName1","lastName1","College1","24","25","Street","23","City1", "country1"]
How can I achieve the above? I tried the below method but not sure how to get all curly braces and brackets into the pattern.
private static String flattenPigBag(String pigdata) {
String s = "";
Pattern p = Pattern.compile("\\{(.*)}");
Matcher m = p.matcher(pigdata);
while (m.find()) {
s = m.group(1);
System.out.println("answer : " + s);
}
return s;
}
Try this:
String[] parts = str.replaceAll("}|\\{", "").split(",");
Are you forced to use a pattern? If not, feel free to use this.
private static List<String> flattenPigBag(String s) {
return Arrays.asList(s.replaceAll("[(){}]", "").split(","));
}
Output:
[firstName1, lastName1, College1, 24, 25, Street, 23, City1, Country1]
I assume you need to extract the individual fields for further processing. So here is what I would do. In my test program I just print out the fields, but I imagine in your program you may take those field values and use them somehow (e.g. apply them to some setters of a Java object)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatchingWithNamedCaptureGroup {
public static void main(String[] args) {
String regex = "\\{(\\("
+ "(?<firstName>[^,]*)"
+ ",(?<lastName>[^,]*)"
+ ",(?<college>[^,]*)"
+ ",\\{\\("
+ "(?<num1>\\d*)"
+ ",(?<num2>\\d*)\\)\\}"
+ ",\\{\\((?<street>[^,]*)"
+ ",(?<streetNum>\\d*)\\)\\}"
+ ",(?<city>[^,]*)"
+ ",(?<country>[^,]*)"
+ "\\))\\}";
String input
= "{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
String firstName = m.group("firstName");
String lastName = m.group("lastName");
String college = m.group("college");
String num1 = m.group("num1");
String num2 = m.group("num2");
String street = m.group("street");
String streetNum = m.group("streetNum");
String city = m.group("city");
String country = m.group("country");
System.out.println(firstName
+ "," + lastName
+ "," + college
+ "," + num1
+ "," + num2
+ "," + street
+ "," + streetNum
+ "," + city
+ "," + country
);
} else {
System.err.println("Does not match!");
}
}
}
The output of this program is this:
firstName1,lastName1,College1,24,25,Street,23,City1,Country1
Sorry, I'm a bit clueless when it comes to this and I'm having a bit of trouble with this specific portion of my program.
The goal is, when someone inputs a three word string, to rearrange it in such a way that "Emma Charlotte Leonard" becomes " Leonard, Emma, C".
This is what I have so far for that specific method:
public String lastFirst (String str)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String lastFirst = keyboard.nextLine();
String middleAndLast = lastFirst.substring(lastFirst.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = lastFirst.substring(0, lastFirst.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
Any help would be appreciated, sorry if I haven't put enough information.
I believe this is what you are trying to achieve:
public class RearrangeName{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String inputStr= keyboard.nextLine();
System.out.println(lastFirst(inputStr));
}
public static String lastFirst (String str){
String middleAndLast = str.substring(str.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = str.substring(0, str.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
}
See the Demo here
Do you want output to be "Leonard, Charlotte, L" or "Leonard, Emma, C".
Current output of your program is the second option. And if you desired first output then you should declare middleInitial as String middleInitial =last.charAt(0);.
Try following example it is return the "Emma Charlotte Leonard" as " Leonard, Charlotte, L"
public class Example{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example exp = new Example();
System.out.print("Enter your number : ");
System.out.println(exp.getName(input.nextLine()));
}
private String getName(String name){
String arr[] = name.split(" ");
return arr[2]+ ", "+arr[1]+", "+arr[2].substring(0, 1);
}
}
this is my code
//Numbers (Need errors on sort and numbers)
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[0] + " ");
String text = "var " + LineSplit[1] + "=" + LineSplit2[0] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
}
}
the line of text is
n number 1
the output should be
var number = 1;
but the output is
var number=n number = 1;
can some one please tell me how to fix this? the code looks right but doesn't work :(
String line = "n number 1";
String JAVASCRIPTTextToWrite="";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[1] + " ");
System.out.println( LineSplit[1]);
System.out.println( LineSplit2[0]);
String text = "var " + LineSplit[1] + "=" + LineSplit2[1] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
System.out.println(JAVASCRIPTTextToWrite);
}
}
String number = "n number 1";
Sting[] temp = number.split(" ");
StringBuilder sb = new StringBuilder("var ");
sb.append(temp[1]);
sb.append(temp[2]);
perform this operation if your condition satisfied
String line = "n number 1";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n")) {
//split the already split line with "n thename "
String LineSplit2 = line.substring(line.lastIndexOf(" ") + 1 , line.length());
String text = "var " + LineSplit[1] + "=" + LineSplit2 + ";";
//text = text.replace("\n", "").replace("\r", "");
System.out.println(text);
}
}
Output:
var number=1;
I do not know what is your purpose for split the string twice. Just for the out put you want, I think the solution below is enough. Please look at the code below whether is you want:
String line = "n number 1";
String JAVASCRIPTTextToWrite = "";
//Numbers (Need errors on sort and numbers)
if(line.contains("n")) {
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit.length == 3) {
StringBuilder text = new StringBuilder();
text.append("var ");
text.append(LineSplit[1]);
text.append("=");
text.append(LineSplit[2]);
text.append(";");
JAVASCRIPTTextToWrite += text.toString().replace("\n", "").replace("\r", "");
System.out.println(JAVASCRIPTTextToWrite);
}
}
I want to get the following output:
Hello Steve Andrews!
These are my variables:
a = "steve";
b = "Andrew"
I tried this:
System.out.print("Hello " + a + " " + b + "s");
I don't know where to put .toUpper() for steve. The s should be in uppercase. How do I do this?
Use StringUtils.capitalize(a),
"Hello " + StringUtils.capitalize(a) + " " + b + "s"
Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.
You could use StringUtils.capitalize(str), or if you want to do it by yourself:
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
You could also try using this method:
public static String capitalize(String str) {
str = (char) (str.charAt(0) - 32) + str.substring(1);
return str;
}
Though it should be noted that this method assumes that the first character in str is indeed a lowercase letter.
Finally, I tried to do it without stringutils.. But anyways, thanks to all who helped :)
public class Hello
{
public static void main(String[] args){
String a = "steve";
String b = "Andrew";
String firstletter = a.substring(0,1);
String remainder = a.substring(1);
String capitalized = firstletter.toUpperCase() + remainder.toLowerCase();
System.out.print("Hello " + capitalized + " " + b + "s" );
}
}