I am trying to remove the last character from a string, if it is a /. I am using a string array, temp[], to store the strings.
Here's my code:
char ch = ' ';
for (int st = 0; st < temp.length; st++)
{
ch = temp[st].charAt(temp[st].length()-1);
if (ch == '/')
temp[st] = temp[st].substring(0, temp[st].length()-1);
result2.append(temp[st]);
}
but i am getting
StringIndexOutOfBoundsException -1
What am I doing wrong?
Remove Last Character if it is / java
str = str.replaceAll("/$", "");
If you only want to remove a trailing '/', this should do it:
if (str.endsWith("/"))
return str.substring(0,str.length()-1);
else
return str;
You could do it with a regex using the replaceFirst(regex, string) method:
String newString = tmp.replaceFirst("/$", "");
The StringUtils have this subtle little method called: removeEnd(String str, String remove)
String result = StringUtils.removeEnd(string, "/")
It will remove the end of the string only if it is this searched snippet. Otherwise this method returns the same, unchanged string.
If you have empty String "" then temp[st].length()-1 == -1
Related
I have been set a task to convert each char in a string to * except for any spaces in that string (the string is user input), the one caveat is that I must use a for loop. My code is below... the current problem that I am having is that when I try to use the char in an if statement condition I am getting a "Type mismatch: cannot convert from char to Boolean" error. All help appreciated...
public static void main(String[] args) {
//declare vars
Scanner input = new Scanner(System.in);
String name = "";
int length = 0;
//get name string
System.out.println("Enter your name");
name = input.nextLine();
//get length of name string
length = name.length();
//convert name string to array of characters
char[] nameChars = name.toCharArray();
//iterate over array of chars replacing each
// char with * and space with space
for (int index=0;index==length;index++){
//if the char is a space then do nothing
if (nameChars[index] = ' ') {
//else convert to *
} else {
nameChars[index] = '*';
}
}
//convert array back to string and output
String newName = new String(nameChars);
System.out.println(newName);
//close resources
input.close();
}
Instead of writing all that code, try this:
String newName = name.replaceAll("\\S", "*");
The regex \S matches "any non whitespace character".
Use == in place of = for the if condition checking as == is the relational operator while = is the assignment operator.
Change index==length to index < length otherwise your loop will never run! Initially index = 0 while length is some positive value and index!=length then. So the loop will never run.
You have to use == instead of = like below:
if (yourChar == ' ') {
//your code ...
}
Try the below approach
if (nameChars[index] == ' ') {
//else convert to *
} else {
nameChars[index] = '*';
}
If you want to use your code, then your condition is wrong, you're affecting the space char to the current char if the string nameChars[index] = ' ' you must change it to nameChars[index] == ' ', note the double equal signe ==.
However, I suggest you use this simple condition, cause you'll not do anything when the current char is a space char, then you don't have to check if it's a space char:
if (nameChars[index] != ' ') {
nameChars[index] = '*';
}
Why do you want to invent a bicycle?
It's better to use the power of Java and exactly replaceAll method of String.class:
String input = "123 wer 456 zxcv!";
String result = input.replaceAll("[^ ]", "*");
System.out.println(result);
Java: how to convert each char in a string to '*' except for spaces
You can just do it in one line without any loops..
String str = pw.replaceAll("[^\\s]", "*");
TEST:
String str1 = "ASDAS sad!## !##^% ?".replaceAll("[^\\s]", "*");
System.out.println(str1);
OUTPUT:
***** ****** ***** *
Note: For char[], you can use String.valueOf(yourArray).replaceAll().
String text = "It is a string";
System.out.println(text.replaceAll("[a-zA-Z]", "*"));
Output for the code will be : ** ** * ******.
Note that it's easier to use a StringBuilder when you want to modify String. You need to remember that Strings are immutable.
I need to replace all commas after the 5th one. So if a String contains 10 commans, I want to leave only the first 5, and remove all subsequent commas.
How can I do this ?
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = sentence.replaceAll(",[6]","");
Just capture all the characters from the start upto the 5th comma and match all the remaining commas using the alternation operator |. So , after | should match all the remaining commas. By replacing all the matched chars with $1 will give you the desired output.
sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");
DEMO
In case you were wondering how to solve this problem without using regular expressions... There are libraries that could make your life easier but here is the first thought that came to mind.
public String replaceSpecificCharAfter( String input, char find, int deleteAfter){
char[] inputArray = input.toCharArray();
String output = "";
int count = 0;
for(int i=0; i <inputArray.length; i++){
char letter = inputArray[i];
if(letter == find){
count++;
if (count <= deleteAfter){
output += letter;
}
}
else{
output += letter;
}
}
return output;
}
Then you would invoke the function like so:
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = replaceSpecificCharAfter(sentence, ',', 6);
I have look into most of questions but I couldn't find how to uppercase or lowercase specific character inside a word.
Example:
String name = "Robert"
What if I would like to make "b" Uppercase and rest lowercase also how to make first letter Uppercase and rest lowercase?
Like "john" >> Output >> "John"...
I have toUppercase() and toLowercase(). They convert the whole text.
Also I tried to include charAt but never worked with me.
You will need to take your string, take a substring of the specific character or characters you want to capitalize or lowercase, and then build a new string off of it.
Example
String test = "JoHn"; //make the H lowercase
test = test.substring(0,2) + test.substring(2,3).toLowercase() + test.substring(3);
The first substring gets all characters before the desired point, the second gets the desired character and lowercases it, and the final substring gets the rest of the string
You can use toCharArray() to capitalize the first letter like this:
String name = "robert";
// Convert String to char array.
char[] arr = name.toCharArray();
// Modify first element in array.
arr[0] = Character.toUpperCase(arr[0]);
String str = new String(arr);
System.out.println(str);
Output:
Robert
And you want to make "b" Uppercase and rest lowercase like this:
// Convert String to char array.
char[] arr2 = name.toCharArray();
// Modify the third element in array.
arr2[2] = Character.toUpperCase(arr2[2]);
String str2 = new String(arr2);
System.out.println(str2);
Output:
roBert
//Try this...
String str = "Robert";
for (int i = 0; i < str.length(); i++) {
int aChar = str.charAt(i);
// you can directly use character instead of ascii codes
if (aChar == 'b') {
aChar = aChar - 32;
} else if (aChar >= 'A' && aChar <= 'Z') {
aChar += 32 ;
}
System.out.print((char) aChar);
}
/*
Output will be- roBert
*/
I wouldn't use 'test.substring(2, 3).toLowerCase()' necessarily. 'Character.valueOf(test.charAt(2)).toUpperCase()' works. Also, the 'test.substring(0, 3)' is wrong; it should be 'test.substring(0, 2)'.
A function that capitalize the first letter
private String capitalize(String str) {
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
A function that capitalize an arbitrary letter
private String replaceCharWithUpperCase(char letterToCapitalize, String str)
{
return str.replaceAll(letterToCapitalize, Character.toUpperCase(letterToCapitalize));
}
Then you can use the previous functions like that :
String a = "JOHN";
a = capitalize(a.toLowerCase());
// now a = John.
String b = "ROBERT";
a = replaceCharWithUpperCase('b', a.toLowerCase());
// now a = roBert.
Java String trim is not removing a whitespace character for me.
String rank = (some method);
System.out.println("(" + rank + ")");
The output is (1 ). Notice the space to the right of the 1.
I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.
The string rank just remains the same either way.
Edit: Full Code::
Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get();
Element table = doc.select("table").get(7);
Elements rows = table.select("tr");
for (Element row: rows) {
String rank = row.select("span").first().text().trim();
System.out.println("("+rank+")");
}
Why can't I remove that space?
The source code of that website shows the special html character . Try searching or replacing the following in your java String: \u00A0.
That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails
rank = rank.replaceAll("\u00A0", "");
should work. Maybe add a double \\ instead of the \.
You should assign the result of trim back to the String variable. Otherwise it is not going to work, because strings in Java are immutable.
String orig = " quick brown fox ";
String trimmed = original.trim();
The character is a non-breaking space, and is thus not removed by the trim() method. Iterate through the characters and print the int value of each one, to know which character you must replace by an empty string to get what you want.
Are you assigning the String?
String rank = " blabla ";
rank = rank.trim();
Don't forget the second assignment, or your trimmed string will go nowhere.
You can look this sort of stuff up in the API as well: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
As you can see this method returns a String, like most methods that operate on a String do. They return the modified String and leave the original String in tact.
I had same problem and did little manipulation on java's trim() method.
You can use this code to trim:
public static String trimAdvanced(String value) {
Objects.requireNonNull(value);
int strLength = value.length();
int len = value.length();
int st = 0;
char[] val = value.toCharArray();
if (strLength == 0) {
return "";
}
while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) {
st++;
if (st == strLength) {
break;
}
}
while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) {
len--;
if (len == 0) {
break;
}
}
return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value;
}
Trim function returns a new copy of the string, with leading and trailing whitespace omitted.
rank = rank.trim();// This will remove and save rank without leading and trailing spaces
will give the result you want.
Replace method will not work if you pass empty string for replacement.
Since String in java are immutable ie they cannot be changed. You need to reassign it to some temporary string. And then using that string you can convert it into int.
String temp=rank.trim()
int te= Integer.parseInt(temp)
I am practicing over the summer to try and get better and I am a little stuck on the following:
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
Examples:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java API and click on String in the lower left pane. That pane is sorted alphabetically.
Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:
String temp = new String(charArray);
and return that. This is assuming that charArray is your array of chars.
Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.
Furthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. Since the return is not picked up in the code above, the String.replace calls really don't do much here.
This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.
Also to add, this approach won't work well with Strings that have a length of 1. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.
Frankly, the approach presented in indyK1ng's answer, where the char[] is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char[] is starting to sound much more pleasant.
String instances in Java are immutable. This means that you cannot change the characters in a String; a different sequence of characters requires a new object. So, when you use the replace method, throw away the original string, and use the result of the method instead.
For this method, however, you probably want to convert the String instance to an array of characters (char[]), which are mutable. After swapping the desired characters, create a new String instance with that array.
A couple of hints:
Strings are immutable, meaning they cannot be changed. Hence, str.replace() does not change str, instead it returns a new string.
Maybe replace isn't the best... Consider frontBack("abcabc"): your function, if it were corrected, would replace 'a' with 'c' yielding "cbccbc", then 'c' with 'a' yielding "abaaba". That's not quite right!
The replace method in String actually returns a String, so if you were to insist on using replace, you'd do:
beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );
But this actually doesn't solve your specific problem, because replace replaces all occurences of a character in the string with its replacement.
For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."
Yet another example without creating additional objects:
if (str.length() > 1) {
char[] chars = str.toCharArray();
// replace with swap()
char first = chars[0];
chars[0] = chars[chars.length - 1];
chars[chars.length - 1] = first;
str = new String(chars);
}
return str;
Edit: Performing the swap on length = 1 string is no-op.
Edit 2: dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.
You could use a regex..
return str.replaceFirst("(.)(.*)(.)", "$3$2$1");
Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.
public static String exchange(String s) {
int n = s.length();
if (n < 2)
return s;
return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}
Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)
if (s.length < 2) {
return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);
(untested, indexes may be of by one...
public String frontBack(String input)
{
return
input.substring(input.length() - 1) + // The last character
input.substring(1, input.length() - 1) + // plus the middle part
input.substring(0, 1); // plus the first character.
}
You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.
public String lastChars(String a, String b) {
if(a.length()>=1&&b.length()>=1){
String str = a.substring(0,1);
String str1 =b.substring(b.length()-1);
return str+str1;
}
else if(a.length()==0&&b.length()==0){
String v ="#";
String z ="#";
return v+z;
}
else if(a.length()==0&&b.length()>=1){
String s ="#";
String s1 = b.substring(b.length()-1);
return s+s1;
}
else if(a.length()>=1&&b.length()==0){
String f= a.substring(0,1);
String h = "#";
return f+h;
}
return a;
}
You can use this code:
public String frontBack(String str) {
if (str.length() <= 1)
return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
class swap
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("no of elements in array");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Elements");
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=a[i];
}
int end=n-1;
b[0]=b[end];
b[end]=a[0];
for(int i=0;i<n;i++)
{
System.out.println(b[i]);
}
}
}
if (str.length() <= 1) {
return str;
}
String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
function frontBack(str: string) {
return str.slice(str.length - 1) + str.slice(1, -1) + str.slice(0, 1)
}
Slice will "cut out" the last letter. Counting the length of the string which is str.length -1, (plus) the reminder sliced string which starts at index 1 and is the last character which expressed at index -1, (plus) sliced last letter which is at index 0 through index 1.