Replacing a character in a character array - java

I have the following program and I am trying to replace the space in the character array with "%20".
For example, if I have this ['a','b',' '], the output would be this ['a','b','%20'].
This is the program:
import java.util.*;
import java.util.Scanner;
class some_str
{ String str1;
String space_method(String str)
{
char[] chars = str.toCharArray();
//char[] s3=new char[chars.length];
for(char c:chars)
//for (int i=0;i<chars.length;i++)
if(Character.isWhitespace(c))
{
//over here I need to replace the space with '%20'
}
return "\n"+str;
}
}
public class space_str
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter string");
String str= sc.nextLine();
some_str st=new some_str();
System.out.println(st.space_method(str));
}
}
Please help, thanks.

Try this:-
str.replace(" ", "%20");
This method replace all spaces with %20 substring and not char because %20 is not a char.

This is what you want:
String replaceSpace(String string) {
StringBuilder sb = new StringBuilder();
for(char c : string.toCharArray()) {
if (c == ' ') {
sb.append("%20");
} else {
sb.append(c);
}
}
return sb.toString();
}
Note that you can't put "%20" into a char, because it is 3 symbols, not 1. That's why you shouldn't use arrays for this purpose.
With library functions you can use either string.replace(" ", "%20") or string.replaceAll(" ", "%20").

We know that Strings are immutable so to replace all the space characters with the %20 in our string, we can either first convert our String to the array of characters which is what you did and manipulate or we can use StringBuilder class, which you can think of as a mutable string but it is basically an array of chars internally. (There is also StringBuffer which essentially does the same thing as StringBuilder except it is thread safe).
Anyways, this following program does what you need to do.
public String spaceMethod(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (Character.isWhitespace(str.charAt(i))) {
sb.append("%20");
}
else
{
sb.append(str.charAt(i));
}
}
return sb.toString();
}
Regarding the error in your code, the answer by Wow has already explained it. Good luck!

Related

How to write a Java program to include whitespaces at the beginning of a string that we want to reverse?

I want to reverse a string.
input: Computer;
This input contains 4 whitespaces in the beginning of the word 'computer'.I want to include these 4 whitespaces in the beginning of the reversed string also.So,the program should include all the whitespaces I put at the beginning while taking the reverse too(I put 4 whitespaces as an example only).
output:" retupmoc";
I am attaching my code here.
package BasicTesting;
import java.util.*;
public class Corrected_StringRev {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();
String reversed = reverseString( str );
System.out.println( reversed );
}
public static String reverseString( String newString ) {
char ch[]=newString.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
How can I change this code to include the above requirement.Please,rewrite the code.Hope ypu will help.Thanks in adavance!
The logic is simple:
Traverse the start of the string and add whitespaces to rev until you meet the first non-whitespace
Do your string reversal and stop before the whitespace section begins
public static String reverseString(String newString) {
char ch[] = newString.toCharArray();
String rev = "";
int nWhitespace;
for (nWhitespace = 0; nWhitespace < ch.length; nWhitespace++) {
if (!Character.isWhitespace(ch[i]) {
break;
}
rev += ch[i];
}
for(int i = ch.length - 1; i >= nWhitespace; i--){
rev += ch[i];
}
return rev;
}
By the way, you can improve your code by using StringBuilder instead of +=.
Here instead of keeping a count and then adding it, we will be checking if the character we are at currently in the string is a whitespace character. If yes, we add a space to our string builder.
As soon as we come across a non-whitespace character, we break out of the loop.
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
What this code does is:
Take string inputString and trim it (remove trailing and leading whitespaces.
Creates a new (anonymous) object of a StringBuilder and reverses it.
Convert it into a string to append it to our original StringBuilder strB after the whitespaces.
Finally, we convert it into String and return it.
Some tips:
I will be using StringBuilder as it is mutable so saves space and also it contains a function to reverse it directly.
You should not call the length function of string in the loop as it will call it for every loop. Better to store the value in a variable and use that variable in the loop.
public static String reverseString(String inputString) {
StringBuilder strB = new StringBuilder();
int len = inputString.length();
for (int i = 0; i<len && inputString.charAt(i) == ' '; i++) {
strB.append(" ");
}
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
}

How do I replace more than one type of Character in Java String

newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string

How to make a String into a new one with only lowercase letters (no spaces, apostrophes) using a loop

I need a way to turn sentences into just a String of lowercase letters, i.e. no spaces, apostrophes or anything while using a loop.
static String toAlphaLowerCase( String s )
{
String c;
for(int i = 0; i < s.length(); i++)
c = s.charAt(i);
if (Character.isLetter())
return c.toLowerCase();
}
Simple: read about the StringBuilder class. You create an instance of that class before your loop. Then during that loop you add all characters you want to be in your result.
Finally, you call toString() on that builder object and return the result of that call.
Right now you are stopping (returning) after the first letter, and that simply skips all following content.
Use a StringBuilder when concatenating the output. String.charAt(int) returns a char, so you will need a char to use that. And Character.isLetter(char) takes a char. Use braces, because omitting them makes the code harder to reason about (and leads to defects such as your code has). Something like,
static String toAlphaLowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLetter(c)) {
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
or use String.toCharArray() and iterate the input with a for-each loop. Like,
static String toAlphaLowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
or use a regular expression, like
static String toAlphaLowerCase(String s) {
return s.toLowerCase().replaceAll("[^a-z]", "");
}

Making first letter capital using regex like in ucwords

I need to convert a String value in to Upper case (First letter to upper in every word).
This can be done in php by using ucwords() method.
Ex :
String myString = “HI GUYS”;
myString = myString. toLowerCase().replaceAll(“Regex”, “Some Charactor”)
Thanks with hi5
Using regex, it will be difficult. Try following simple code:
String str="hello world";
String[] words=str.split(" ");
for (String word : words) {
char upCase=Character.toUpperCase(word.charAt(0));
System.out.print(new StringBuilder(word.substring(1)).insert(0, upCase));
}
Output:
Hello World
Undermentioned will work great in all your situation
If you need to get first letter of all words capital ..
-----------------------------------------------------
public String toTheUpperCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
When you need first letter of first word to be capitalized
-------------------------------------------------------------
public String toTheUpperCaseSingle(String givenString) {
String example = givenString;
example = example.substring(0, 1).toUpperCase()
+ example.substring(1, example.length());
System.out.println(example);
return example;
}
How to use :: Try defining this code n your super class ( Best code practice )
Now when u need to use this method .. just pass String which you need to transform .
For Ex:: Let us assume our super class as CommanUtilityClass.java ...
Now you need this method in some activity say " MainActivity.java "
Now create object of super class as :: [ CommanUtilityClass cuc; ]
Final task -- use this method as described below:
your_text_view.setText(cuc.toTheUpperCase(user_name)); // for all words
your_text_view.setText(cuc.toTheUpperCaseSingle(user_name)); // for only first word ...
Let me know if you need more details for that ..
Enjoy
Cheers !
System.out.println(ucWord("the codes are better than words !!"));// in main method
private static String ucWord(String word) {
word = word.toLowerCase();
char[] c = word.toCharArray();
c[0] = Character.toUpperCase(c[0]);
int len = c.length;
for (int i = 1; i < len; i++) {
if (c[i] == ' ') {
i++;
c[i] = Character.toUpperCase(c[i]);
}
}
return String.valueOf(c);
}
You can use WordUtils from apache for same purpose,
WordUtils.capitalizeFully(Input String);
Here are simplified versions of the toUpperCase methods.
Change all first letters in the sentence to upper case.
public static String ucwords(String sentence) {
StringBuffer sb = new StringBuffer();
for (CharSequence word: sentence.split(" "))
sb.append(Character.toUpperCase(word.charAt(0))).append(word.subSequence(1, word.length())).append(" ");
return sb.toString().trim();
}
Change only the first word to upper case. (nice one-liner)
public static String ucFirstWord(String sentence) {
return String.valueOf(Character.toUpperCase(word.charAt(0))).concat(word.substring(1));
}
String stringToSearch = "this string is needed to be first letter uppercased for each word";
// First letter upper case using regex
Pattern firstLetterPtn = Pattern.compile("(\\b[a-z]{1})+");
Matcher m = firstLetterPtn.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,m.group().toUpperCase());
}
m.appendTail(sb);
stringToSearch = sb.toString();
sb.setLength(0);
System.out.println(stringToSearch);
output:
This String Is Needed To Be First Letter Uppercased For Each Word

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));
}
}

Categories