Im a beginner java programmer and I am stuck on a little problem with my university coursework.
Basically I have a string that I want to iterate through and replace all instances of the letter 'a' or 'e' with the letter 'z'. For example, if the original string was "hello alan", the final string should be "hzllo zlzn".
We need to do this using a character array which holds the characters 'a' and 'e' to test against the string.
I've included my code below, we need to use the charAt() method also.
public static void main(String[] args) {
String a = ("what's the craic?");
char letters[] = new char[]{'a', 't'};
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a, letters));
}
public static String removeCharacters(String sentence, char[] letters) {
for (int i = 0; i < sentence.length(); i++) {
for (int j = 0; j < letters.length; j++) {
if (sentence.charAt(i) == letters[j]) {
sentence = sentence.replace(sentence.charAt(i), 'z');
} else {
sentence = "No changes nessesary";
}
}
}
return sentence;
}
Please help me with this problem. Im not sure where I am going wrong! Thanks.
if You are allowed to use replaceAll as well
"hello alan".replaceAll( "[ae]", "z" ); // hzllo zlzn
In difference to replace uses replaceAll a Pattern internally, which is compiled from the first argument [ae] to find the part to substitute with the second argument z. This solution is elegantly short, but slow, because the Pattern has to be compiled each time replaceAll is called.
otherwise use a StringBuilder
char[] letters = new char[] { 'a', 'e' };
StringBuilder buf = new StringBuilder( "hello alan" );
IntStream.range( 0, buf.length() ).forEach( i -> {
for( char c : letters )
if( buf.charAt( i ) == c )
buf.replace( i, i + 1, "z" );
} );
String s = buf.toString(); // hzllo zlzn
In difference to a String the contents of a StringBuilder is mutual (means you can change it). So it only has to be created once and all substitutions can be made in place.
Try this:
public static void main(String[] args) {
String a = "hello alan";
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a));
}
public static String removeCharacters(String sentence) {
if (!sentence.contains("a|e"))
return "No changes necessary";
return sentence.replaceAll("a|e", "z");
}
output 1:
Before:hello alan
After: hzllo zlzn
output 2:
Before:hi world
After: No changes necessary
Since you're forced to use charAt(...), one way would be like this:
public static String removeCharacters(String sentence, char[] letters) {
String output = "";
boolean wasChanged = false;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
for (int j = 0; j < letters.length; j++)
if (ch == letters[j]) {
ch = 'z';
wasChanged = true;
break;
}
output += ch;
}
if (wasChanged)
return output;
else
return "No changes necessary";
}
Since String::replace(char oldChar, char newChar) returns a new string resulting from replacing all occurrences of oldChar in this string with newChar, you do not need nested loops to do it. An efficient way of doing it can be as follows:
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
Demo:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(removeCharacters("hello stackoverflow", new char[] { 'a', 'e' }));
System.out.println(removeCharacters("world", new char[] { 'a', 'e' }));
}
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
}
Output:
hzllo stzckovzrflow
No changes nessesary
The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. I have provided a proposed solution at the end of my code snippet below.
public static char getKeyCharacter(String userInput) {
char keyCharacter;
Scanner inputStream = new Scanner(System.in);
while(userInput.length() > 1)
{
System.out.println("Please enter a SINGLE character to use as key: ");
userInput = inputStream.nextLine();
}
keyCharacter = userInput.charAt(0);
return keyCharacter;
}
public static String getString(String userResponse) {
Scanner inputStream = new Scanner(System.in);
String theString;
while(userResponse.length() > 500) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
while(userResponse.length() < 4) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
theString = userResponse;
return theString;
}
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
maskedString = maskedString + theString.replace(keyCharacter, mask);
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
public static String removeCharacter(String theString, char keyCharacter) {
String modifiedString = " ";
final char replaceChar = ' ';
modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
System.out.println("String with " + keyCharacter + " removed:");
return modifiedString;
}
public static int countKey(String theString, char keyCharacter) {
int charCount = 0;
for (int c = 0; c < theString.length(); c++) {
if (theString.charAt(c) == keyCharacter) {
charCount++;
}
}
System.out.println("Occurences of " + keyCharacter + " in string:");
return charCount;
}
}
I believe the solution is will look something like this, but thus far I've been unsuccesful -
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
for (int k = 0; k < theString.length(); k++) {
if (theString.charAt(k) == keyCharacter) {
keyCharacter = mask;
}
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. Thank you for the assistance in advance!
I would use a StringBuilder and String#toCharArray() with a simple for-each loop. Like,
public static String maskCharacter(String theString, char keyCharacter){
StringBuilder sb = new StringBuilder();
for (char ch : theString.toCharArray()) {
if (ch == keyCharacter) {
sb.append('$'); // <-- mask keyCharacter(s).
} else {
sb.append(ch); // <-- it isn't the character to mask
}
}
return sb.toString();
}
I wouldn't use a StringBuilder: just use the result of toCharArray() directly:
char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);
Not only is it more concise, but:
It will run faster, because it's cheaper to access an array element than to invoke a method; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that);
It will use less memory, because it doesn't require storage for the copy inside StringBuilder.
public static String maskCharacter(String theString, char keyCharacter){
String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {
if (theString.charAt(i) == keyCharacter) {
masked += "$";
}
else {
masked+=theString.charAt(i)+"";
}
}
return masked;
}
An answer that only uses string concatenation and basic character access.
You seem to know that you can concatenate something to a string and get a different string.
maskedString = maskedString + ...;
You also know you can build a for-loop that gets each individual character using .charAt()
for (int k = 0; k < theString.length(); k++) {
char nch = theString.charAt(k);
}
You can check equality between chars
if (nch == keyCharacter)
... assuming you know about else-branches, isn't it clear you just need to put them together?
if (nch == keyCharacter) {
// append '$' to maskedString
}
else {
// append nch to maskedString
}
Of course this creates a new string on every loop iteration so it is not terribly efficient. But I don't think that's the point of the exercise.
I'm trying to convert some text so that every even character becomes uppercase. This works, but if there's a space between words, the code takes the space as a character too. So for example, if the input text is "this is a test", the output is "tHiS Is a tEsT". I want it to ignore the spaces and give "tHiS iS a TeSt" as output.
I now have the following code:
private String result;
private String letter;
private void generateText() {
result = "";
String input = editTextInput.getText().toString();
String lowerCase = input.toLowerCase();
char[] charArray = lowerCase.toCharArray();
for(int i=0;i<charArray.length;i++){
if(String.valueOf(charArray[i]).equals(" ")){
//I don't know what to put here
letter = String.valueOf(charArray[i]);
}else{
if(i%2 == 0){
letter = String.valueOf(charArray[i]);
}else if(i%2 == 1){
letter = String.valueOf(charArray[i]).toUpperCase();
}
}
result += letter ;
}
Log.d("result", result);
}
What do I have to do to skip the spaces?
If it's possible, I would like to skip punctuation marks too, or in general, every character which is not a letter.
Thanks in advance!
(For those who are wondering, I'm making a Spongebob meme text generator app)
If you want to do alternate logic in a loop, you could normally use i % 2 == 0, or (i & 1) == 1, but since the alternation is conditional, you need a variable to store the "state". With simple alternation, a boolean variable is the obvious choice.
Also, continuously converting each char to a String is bad for performance. Just update the char[].
private static String upperEven(String input) {
char[] buf = input.toLowerCase().toCharArray();
boolean upper = false;
for (int i = 0; i < buf.length; i++) {
if (Character.isLetter(buf[i])) {
if (upper)
buf[i] = Character.toUpperCase(buf[i]);
upper = ! upper;
}
}
return new String(buf);
}
Test
System.out.println(upperEven("this IS a TEST"));
Output
tHiS iS a TeSt
Code can be compressed/obscured to this: ;-)
private static String upperEven(String s) {
char[] c = s.toCharArray();
boolean t = false;
for (int i = 0; i < c.length; i++)
if (Character.isLetter(c[i]))
c[i] = ((t = ! t) ? Character.toLowerCase(c[i]) : Character.toUpperCase(c[i]));
return new String(c);
}
This is my solution.
private static void generateText() {
String result = "";
String input = "i am a engineer and student of nit.";
String lowerCase = input.toLowerCase();
Boolean isLower = false;
char[] charArray = lowerCase.toCharArray();
for (int i = 0; i < lowerCase.length(); i++) {
String letter = String.valueOf(charArray[i]);
if (!Character.isLetter(charArray[i])) {
result += letter;
} else {
if(isLower)
letter = letter.toUpperCase();
result += letter;
isLower = !isLower;
}
}
System.out.println(result);
}
My program worked fine before I tried implementing the conversion options. All I am trying to do is implement a U/u or L/l input option for either convert the string to Uppercase or Lowercase. Help please?
import java.util.Scanner;
public class CaseManipulation {
public static void main(String[] args) {
boolean up, low;
char up[] = {'U', 'u'};
char low[] = {'L', 'l'};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an input String: ");
String inputString = scanner.nextLine();
System.out.print("Case Conversion Option(U/u for uppercase, L/l for lowercase):");
char caseoption = scanner.nextLine();
if (caseoption == up[]) {
System.out.println("Upper Case: " + toUpperCase(inputString));
} else if (caseoption == low[]) {
System.out.println("Lower Case: " + toLowerCase(inputString));
}
//is_uppercase();
//System.out.println("Upper Case: " + toUpperCase(inputString));
//System.out.println("Lower Case: " + toLowerCase(inputString));
}
//public static boolean is_uppercase(char caseoption) {
// if (char caseoption == ) {
// }
//}
public static String toUpperCase(String inputString) {
String result = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
char currentCharToUpperCase = Character.toUpperCase(currentChar);
result = result + currentCharToUpperCase;
}
return result;
}
public static String toLowerCase(String inputString) {
String result = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
char currentCharToLowerCase = Character.toLowerCase(currentChar);
result = result + currentCharToLowerCase;
}
return result;
}
}
Basically, your if condition is comparing the object/memory references of the two objects, not their values...
if (caseoption == up[]) {...
caseoption is never likely to be equal to up...
Instead, you should be comparing their contents...
if (caseoption == up[0] || caseoption == up[1]) {...
A simpler solution might be to convert the caseoption into a single use case, for example...
if (Character.toUpperCase(caseoption) == 'U') {...
I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.