Taking Input of a String Word by Word

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
string t;
getline(cin,t);

istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

How to read User input word by word from one line with scanner?

Here is the answer to your question:

import java.util.Scanner;
public class Test {
static String course;
static double mark;
static int id;
static int times = 1;
static double avgmark;
static void readline(){
System.out.println("Enter student details in the format: [Final creds] [ID] [Course]");
while(true){
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine();
if (userInput.equals("y")){
times++;
System.out.println("Type in your next mark:");
Double nextMark = scanner.nextDouble();
mark += nextMark;
System.out.println("Would you like to add another mark? [y/n]");
continue;
} else if (userInput.equals("n")){
break;
} else if (userInput.matches("^(\\S+(?:\\h+\\S+)*)$")) {
String[] parts = userInput.split(" ");
mark = Integer.parseInt(parts[0]);
id = Integer.parseInt(parts[1]);
course = parts[2];
System.out.println("Would you like to add another mark? [y/n]");
continue;
}
}
avgmark = mark/times;
avgmark *= 100;
avgmark = Math.round(avgmark);
avgmark /= 100;
System.out.println("\nStudent Information: \nID: #"+ id + "\nCourse: " + course + " \nTotal Marks: " + mark +"\nAvg. Mark: "+avgmark + "%");
}
public static void main(String[] args) {
readline();
}
}

Output:

Output

Here is how it works:

In order to scan a line of input with a Scanner, you need to use a regex (or a REGular EXpression). I use the regex matcher ^(\\S+(?:\\h+\\S+)*)$ More info about it here and here! After checking if the userInput is the correct format, split it with the .split(" ") function. This will turn the entire input (EX: 568 Pro 123) into an Array... String[] parts = userInput.split(" ");[568, Pro, 123]. Once the userInput is an Array, you can assign it with variables... String name = parts[1]. This line of code will assign 'Pro' to the variable 'name'. From there, you can use it alongside the other variables that you assign. double gamescore = Integer.parseInt(parts[0]); This line of code assigns '568' to the variable 'gamescore'. Integer.parseInt() is a command that turns a String into a number, so the String 'parts[0]' is turned into a number that can be assigned to a 'double variable'.

User input a word then print letters of the word on a new line for java

You can change your code like that

 import javax.swing.*;
public class Exercise_28 {
public static void main(String[] args) {
String input;
String letters;
int num1;
int num2;

input = JOptionPane.showInputDialog("Enter a word: ");
num1 = input.length() - 1;
num2 = input.length() - num1 - 1;
// letters = input.substring(0, 1);

while (num2 <= num1) {
letters = input.substring(num2, num2 + 1);
System.out.println(letters);
num2++;
}
System.exit(0);
}
}

error occurs when you want substring input without checking your num2 with while

How to take input of a sentence where each word is in a string array, untill user presses enter

You could separate the input string using a simple loop like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
string S;
string strings[5]; // whatever the size
unsigned index = 0;

getline(cin, S);
for (unsigned i = 0; i < S.size(); i++)
{
if (S[i] == ' ')
index++;
else
strings[index] += S[i];
}

for (unsigned i = 0; i < 5; i++) // whatever the size again
cout << strings[i] << endl;
}

Input:

I like big yellow birds

Output:

I
like
big
yellow
birds

How to get word by word as input without getting as an entire string in C?

When the user hits enter, the input stream holds the entire block of input along with the carriage return. From there it's just a matter of reading or formatting it to your liking.

In your case, strtok could work fine so long as you don't care about the punctuation.

#include <stdio.h>
#include <string.h>

int main(void) {

char Stream[1024] = {0};
char* TokenPointer = 0;
const char Token[] = " ";

fgets(Stream,sizeof(Stream),stdin);
TokenPointer = strtok(Stream, Token);
while(TokenPointer != 0)
{
puts(TokenPointer);
TokenPointer = strtok(0,Token);
}
return 0;
}

How to take a string as input and then print each word in a new line

This explicitly violates your condition, but the condition is inappropriate and I think it's worthwhile for the reader to see how to do this without it. The primary benefit of this approach is that you do not impose arbitrary limits on the input length. (In the original code, input must not exceed 100 bytes.) I make the assumption that your problem statement is simply to implement tr -s '[[:space:]]' \\n, in which case you can do:

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

int
main(void)
{
int in_space = 0;
int c;
while( (c = getchar()) != EOF ) {
if(isspace(c)) {
if( !in_space )
putchar('\n');
in_space = 1;
} else {
in_space = 0;
putchar(c);
}
}
if(!in_space)
putchar('\n');
return 0;
}

Which can be simplified somewhat (IMO, the above is excessively redundant):

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

int
main(void)
{
int c;
int last = '\n';
while( (c = getchar()) != EOF ) {
c = isspace(c) ? '\n' : c;
if( c != '\n' || last != '\n' )
putchar(c);
last = c;
}
if( last != '\n' )
putchar(c);
return 0;
}

or even:

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

void
dedup(int c)
{
static int last = '\n';
if( c != '\n' || last != '\n' )
putchar(c);
last = c;
}

int
main(void)
{
int c;
while( (c = getchar()) != EOF ) {
dedup( isspace(c) ? '\n' : c);
}
dedup('\n');
return 0;
}

How do I take a certain word from user input and make it a string?

string userInput = Console.ReadLine();
string color = userInput.Split(' ')[2];

Of course, in a real program, you should check if the string has 3 words before trying to get it from the array returning from the Split() method, something like this:

string userInput = Console.ReadLine();
string[] words = userInput.Split(' ');
if (words.Length >= 3) {
string color = words[2];
Console.WriteLine("The third word is: " + color);
}
else {
Console.WriteLine("Not enough words.");
}

Print the most repeated word in a string

In fact, to get the most frequent word, existing code needs to be modified slightly just to provide a variable for the most repeated variable which has to be updated when a more frequent word is detected. No extra arrays/data structures is needed for this specific task.

String arr[] = str.split(" ");
int maxFreq = 0;
String mostRepeated = null;

for (int i = 0; i < arr.length; i++) {
String temp = arr[i];
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (temp.equalsIgnoreCase(arr[j]))
count++;
}
if (maxFreq < count) {
maxFreq = count;
mostRepeated = temp;
}
}
System.out.println(mostRepeated + ": " + maxFreq);

For the input:

String str = "I am he as you are he as you are me and we are all together";

Output:

are: 3

A bit faster implementation could include setting the duplicated values to null to skip them later:

for (int i = 0; i < arr.length; i++) {
if (null == arr[i]) continue;
String temp = arr[i];
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (temp.equalsIgnoreCase(arr[j])) {
count++;
arr[j] = null;
}
}
if (maxFreq < count) {
maxFreq = count;
mostRepeated = temp;
}
}


Related Topics



Leave a reply



Submit