Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
String ch = "aeiouycbdfgh";
int len = r.nextInt(10) + 10;
StringBuffer sb = new StringBuffer();
for (int i=0; i<len; i++){
sb.append(ch.charAt(r.nextInt(ch.length())));
}
System.out.println("String:" + sb);
System.out.println("Vowels:");
outputVowels(sb.toString());
}
public static void outputVowels(String s){
How do i make a for loop that will output the vowels of the ch string each in a different line?
edit: the program is meant to output
a
e
i
o
u
First prepare global vowel set - for fast access:
Set<Character> vowelSet = new HashSet<>();
vowelSet.addAll(Arrays.asList('a', 'e', 'i', 'o', 'u'));
Second, you can write scanning loop like this:
String str = "ahjuekjdf";
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(vowelSet.contains(c)) {
System.out.println(c);
}
}
You can directly use Regex
public class Test {
public static void main(String[] args) {
String s = "Ankur";
s = s.replaceAll("[^aeiouAEIOU]", "");
System.out.println(s);
}
}
Output
Au
change your loop to
for (int i=0; i<len; i++) {
char c = sh.charAt(i);
if ((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u')) {
sb.append(ch.charAt(r.nextInt(ch.length())));
}
}
for(char v : vowel){
if(ch == v){
cout <<ch<<" is vowel";
break;
}
else{
cout <<ch<<" is consonant";
break;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 20 days ago.
Improve this question
My task is to find number of occurrences of a string character and replace the character with the number of occurrence up to that particular index inside the string
public static void main(String[] args) {
char[] arr = "hello".toCharArray();
arr[2] = '1';
arr[3] = '2';
System.out.println(arr);
}
Output should be: he12o
I know we cant reuse this approach.
what is the output of "helololol"?
output for helololol, ch='l' , then the output should be he1o2o3o4; if ch='o' then output should be hel1l2l3l
If according to this rule, Can be achieved with a loop:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
}
}
System.out.println(str);
}
Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
if (num > 10) {
len++;
}
}
System.out.println(str);
}
}
The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!
Instead of using primitive methods to manipulate string , we can use the following to have clean code .
public static void main(String args[]) {
String str="helolololololololololololololololololololololololololololololololololololo";
String checkString="l";
int count=1;
StringBuilder sb=new StringBuilder();
List<String> strLst= new ArrayList<String>();
for(int i=0;i<str.length();i++) {
strLst.add(String.valueOf(str.charAt(i)));
}
for(String x : strLst) {
if(x.equals(checkString)) {
sb.append(count);
count++;
}else {
sb.append(x);
}
}
System.out.println(sb);
}
The output for the above string will be
he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o
With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
//. I was writing code to get first letters of all words in a string.
public class Firstword {
static void func(String str)
{
String k ="";
String str1=" "+str;
char[] ch= str1.toCharArray();
for(int i=0;i<ch.length-2;i++)
{
if(i != ch.length-1)
while(i<ch.length && ch[i]!=' ')
i++;
k=k+ch[i+1];
}
System.out.print(k);
System.out.print(ch.length);
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
}
Your error is here:
k=k+ch[i+1];
You are getting out of bounds.
Because of this:
while(i<ch.length && ch[i]!=' ')
i++;
Something like this will work -
static void func(String str)
{
String [] words = str.split(" ");
for(int i = 0; i < words.length ;i++){
System.out.println(words[i].charAt(0));
}
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
Output -
H
B
j
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm supposed to print the word in the beginning of the list if it starts with the letters e and s, and print at the end if it starts with any other letter.
For example:
input: band fan egg laura sand
output: sand egg band fan laura
What should I do to make it work? This is what I've done so far:
import java.util.*;
public class list {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
LinkedList<String> names = new LinkedList<String>();
String s = scan.next();
final String[] letters = {"s", "S", "e", "E"};
for (int i = 0; i < letters.length; i++) {
if (s.startsWith(letters[i])) {
names.addFirst(s);
} else {
names.addLast(s);
}
for (int f = 0; f < names.size(); f++) System.out.print(names.get(f) + " ");
}
}
}
Well there are some mistakes you made
s is the whole list the user typed in
you put the for-loop that prints the answer in the letter-reading loop
do println() instead of print()
But, It's ok, we all make mistakes, and you sometimes need help.
So, I'd fix it so it's like this
import java.util.*;
public class list {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
LinkedList<String> names = new LinkedList<>();
String s = scan.nextLine();
List<String> l = new ArrayList<>();
String k = "";
for (int i = 0; i < s.length();i++) {
if (s.charAt(i) == " ".charAt(0)) {
l.add(k);
k="";
} else {
k = k + s.charAt(i);
}
}
final String[] letters = {"s", "S", "e", "E"};
for (String ss : l) {
boolean isfalse = true;
for (String letter : letters) {
if (ss.startsWith(letter)) {
names.addFirst(ss);
isfalse = false;
break;
}
}
if (isfalse) {
names.addLast(ss);
}
}
for (String name : names) {
System.out.println(name);
}}}
I hope this helped you! :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My target is to reverse the string without changing the postion of the words, I want to print "tesT eht tcudorp"
public class roughWork {
public static void main(String[] args) {
String str = "Test the product";
String arr[] = str.split(" ");
for (int i = 0; i < arr.length; i++) {
for (int j = arr[i].length() - 1; j >= 0; j--) {
System.out.print(arr[j] + " ");
}
}
}
}
Your problem is that you're asking it to print the whole string repeatedly in this line: System.out.print(arr[j]+" ");. Changing that to print only an individual character will fix it:
public class roughWork {
public static void main(String[] args) {
String str= "Test the product";
String arr[]=str.split(" ");
for(int i=0;i<arr.length;i++)
{
for(int j=arr[i].length()-1;j>=0;j--)
{
System.out.print(arr[i].charAt(j));
}
System.out.print(" ");
}
}
}
The second print adds the space between each words after it has output all that words characters.
You are almost there just use charAt and print arr[i].charAt(j)
String str = "Test the product";
String arr[] = str.split(" ");
for (int i = 0; i < arr.length; i++) {
for (int j = arr[i].length() - 1; j >= 0; j--) {
System.out.print(arr[i].charAt(j));
}
System.out.print(" ");
}
Demo
class reverse {
public static void main(String[] args) {
String s = "Hello India";
String[] ch = s.split(" ");
for (String chr : ch) {
String rev = "";
for (int i = chr.length() - 1; i >= 0; i--) {
rev = rev + chr.charAt(i);
}
System.out.print(rev + " ");
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to reverse words in string of java without using split method and StringTokenizer.
For example, How are you must be printed in you are How.
I tried but I failed to do it.
Any help will be appreciated.
Try below code snippet
import java.util.ArrayList;
public class ReverseString
{
public static void main(String args[])
{
String myName = "Here we go";
ArrayList al = new ArrayList();
al = recursiveReverseMethod(myName,al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for(int i = al.size()-1; i>=0;i--)
{
sb.append(al.get(i)+" ");
}
System.out.println(sb);
}
public static ArrayList recursiveReverseMethod(String myName,ArrayList al)
{
int index = myName.indexOf(" ");
al.add(myName.substring(0, index));
myName = myName.substring(index+1);
if(myName.indexOf(" ")==-1)
{
al.add(myName.substring(0));
return al;
}
return recursiveReverseMethod(myName,al);
}
}
Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,
class testers {
public static void main(String[] args) {
String testStr="LongString";
testers u= new testers();
u.reverseStr(testStr);
}
public void reverseStr(String testStr){
char[] d= testStr.toCharArray();
int i;
int length=d.length;
int last_pos;
last_pos=d.length-1;
for (i=0;i<length/2;i++){
char tmp=d[i];
d[i]=d[last_pos-i];
d[last_pos-i]=tmp;
}
System.out.println(d);
}
}
I would do this:
public static String reverseWordsWithoutSplit(String sentence){
if (sentence == null || sentence.isEmpty()) return sentence;
int nextSpaceIndex = 0;
int wordStartIndex = 0;
int length = sentence.length();
StringBuilder reversedSentence = new StringBuilder();
while (nextSpaceIndex > -1){
nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
wordStartIndex = nextSpaceIndex + 1;
}
return reversedSentence.toString();
}