Find and output longest string word c++ - c++

I'm pretty new to programming and recently started working with strings. In my mind, this idea should somewhat work, but I have no idea what's wrong.
So I go through the string, with simb++ (to find length of the word) and where++ (to find where in the string am I) until I find a space, where I compare with the longest word I've found so so far (temp) and if it's longer, I make it the longest and find starting point of the word (start). When the for(...) ends, I write the word in the last for()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
string longest="";
int simb=0;
int temp=0;
int where=0;
int start=0;
cout<<"Input sentence"<<endl;
getline(cin,sentence);
for(int i=0 ; i<sentence.size() ; i++)
{
if(sentence[i]!=' ')
{
simb++;
where++;
}
if(sentence[i]==' ')
{
if(simb>temp)
{
where++;
simb++;
start=where-simb;
temp=simb;
}
simb=0;
}
}
for(int m=start ; m<=temp ; m++)
{
longest=longest+sentence[m];
}
cout<<"longest sentence"<<longest<<endl;
return 0;
}

There are a number of issues in your code:
if simb<=temp you don't increment where, you can just remove where completely and use i instead.
incrementing simb before calculating start results in start being 1 less than it should be
you don't check the length of last word in the string (assuming the string doesn't end with whitespace)
your final for loop goes from start to temp but should go from start to start + temp
Fixing these issues gives:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int simb = 0;
int temp = 0;
int start = 0;
string sentence = "test test2 test 3 test 4 foo longest";
for (int i = 0; i <= sentence.size(); i++)
{
if (i != sentence.size() && sentence[i] != ' ')
{
simb++;
}
else
{
if (simb > temp)
{
start = i - simb;
temp = simb;
}
simb = 0;
}
}
string longest = "";
for (int m = start; m < start + temp; m++)
{
longest = longest + sentence[m];
}
cout << "longest sentence: '" << longest << "'\n";
return 0;
}
Note that using std::istringstream would be much simpler:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string sentence = "test test2 test 3 test 4 foo longest";
std::string longest;
std::stringstream ss(sentence);
std::string word;
while (ss >> word)
{
if (word.length() > longest.length())
{
longest = word;
}
}
std::cout << "longest sentence: '" << longest << "'\n";
return 0;
}

You can try this:
1.first locate where the spaces are.
2.calculate the gap between the two consequent words/strings.
3.find the word which has the maximum gap.
4.the world which has the maximum gap will be the longest one.
It's not c++ specific you can try this with any language.
Here is the c++ example:
#include <iostream>
#include <string>
using namespace std;
int main(){
//to get the user input
cout<<"Enter a sentence:"<<endl;
string s;
getline(cin,s);
// here the old value refers to the last index having space
// gap is the difference betweeen latest index having space and the old value
// max stores the maximum gap
int old=0;
int max=0;
int gap=0;
//these two values store the starting and ending index of longest string
int startIndex;
int endIndex;
// This for loop determines the maximum gap and calculates the starting
// and ending index of the longest word.
for(int i=0;i<s.size();i++){
if(isspace(s[i])|| i==s.size()){
if((i-old)>gap){
max=(i-old);
startIndex=i-max;
endIndex=i;}
gap=(i-old);
old=i+1;}
}
cout<<"longest string in the sentence is:";
//here we are using the determined starting and ending indices to print the longest word
for(int i=startIndex;i<=endIndex;i++){
cout<<s[i];
}
return 0;
}

Related

I aim to write a program that will count and store the position of the occurence of a string within a character array

The program will count the position where a specific string occurs within a character array and store that position within an array. As an example the string 'has' would be at positions [0,13,25,33] when compared to the string 'hassan is a hassler who hassles hasslers'. Two main character arrays are being used; str[] and sub[]. str being the string from where the occurrence is counted from and sub the string compared. I have attached my idea of the code. Any help is appreciated and as I am still a student and not a pro, I would very much appreciate constructive help rather than comments on how my code and workflow is sloppy. I wish to display the array with all the positions and the program does not display anything other than the return value, which for some reasons is mostly very big numbers.
#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub;
char str[100]; //i initially wished to use the variable nstr but it wouldnt work with cin.get
char sub[nsub];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
while (nstr1<=nsub)
{
if (n==str[nstr1])
{
outdisplay[num]=nstr1;// this is where i think the problem perhaps lies.
num++;
count++;
}
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}
updated code:
#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub=20;
char str[100];
char sub[20];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
if (n==str[nstr1])
{
outdisplay[num]=nstr1;
num++;
count++;
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}
So the basic idea is to enumerate over every position in the source string and check whether it is the start of your substring.
It is better for you to try implementing the following pseudo-code, and come back if you have any more questions.
# substr_len: The length of the substring you are looking for.
# str_len: The length of the source string.
# result: An array of int with sufficient length.
let match_count = 0
for (i in range 0..str_len-substr_len)
let match = true
for (j in range 0..substr_len-1)
if (substr[j] != str[i + j])
match = false
break
if (match)
result[match_count] = i
match_count = match_count + 1

C++ How to find out most consecutive digits in an array?

Hi guys I'm trying to write a code where when i type a binary string I need to mind the most consecutive numbers of occurrence 1 has occurred. For example, if i type 00111001, it should be 3, 1100111011111, it should be 5 etc. This is my code so far.
int main () {
string s1;
cin >> s1;
int l1=s1.size()-1; // length-1 hence the for loop array doesnt go out of bounds
int max=0; // this tells us the max number of occurrence
int count=0;
for (int i=0;i<l1;i++) {
if (s1[i]=='1' && s1[i+1]=='1') { // if s[0] and s[1] are both 1, it adds 1
count++;}
if (count>0 && count>max)
{max=count; // storing the count value in max.
}
if (s1[i]=='0' || s1[i+1]=='0'){ //resetting count if it encounters 0
count=0;
}
}
max=max+1;
cout << max << '\n' << endl;
The issue is if I write 1111001 it runs (I get 4), but when i type 1100111001 I get 2. Don't get why there's ambiguity. Please let me know what I need to do
Thanks
I'd only increment the count in case of 1, and zero it when 0 is reached.
whenever count is bigger than max, assign count to max and that's it.
btw, I get 3 for the input 1100111001 with your program.
#include <iostream>
using namespace std;
int main() {
string s1;
cin >> s1;
int l1 = s1.size();
int max = 0;
int count = 0;
for (int i = 0; i < l1; i++)
{
if (s1[i] == '1')
{
count++;
}
else
{
count = 0;
}
if (count > max)
{
max = count;
}
}
cout << max << '\n' << endl;
}
Let's solve this using find, given string s1 which contains your input string you can just do:
auto max = 0;
for(auto start = find(cbegin(s1), cend(s1), '1'); start != cend(s1); start = find(start, cend(s1), '1')) {
const auto finish = find(start, cend(s1), '0');
const auto count = distance(start, finish);
if(count > max) {
max = count;
}
start = finish;
}
Live Example
I want to offer you such an option for calculating through tokens and sorting:
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string s1;
cin>>s1;
istringstream s(s1);
vector<string> result;
while (std::getline(s,s1,'0')) {
result.push_back(s1);
}
sort(result.begin(),result.end(),[](const string &a, const string &b){ return a.length()>b.length();});
cout << result.at(0).length() << endl;
return 0;
}

C++ Program to print the longest word of the string?

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";
for (int i = 0; i < len; i++)
{
if(s[i] != ' ')
{
counter++;
}
if(s[i] == ' ' || i == len - 1)
{
if(counter > max_word)
{
max_word = counter;
//handling end of string.
if(i == len - 1)
max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
else
max = s.substr(i - max_word, max_word);
}
counter = 0;
}
}
cout << max_word << " " << max << endl; #output
return 0;
}
The current output is '4 This' on entering the string "This is cool".
How do I get it to print '4 This; Cool' ?
On running it in Linux through the terminal, it gives me the error
" terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped) "
If I have understood you correctly then you mean the following
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s;
std::getline( std::cin, s );
std::string::size_type max_size;
std::string max_word;
std::string word;
std::istringstream is( s );
max_size = 0;
while ( is >> word )
{
if ( max_size < word.size() )
{
max_size = word.size();
max_word = word;
}
else if ( max_size == word.size() )
{
max_word += "; ";
max_word += word;
}
}
std::cout << max_size << ' ' << max_word << std::endl;
}
If to enter string
This is cool
then the output will be
4 This; cool
The basic idea here is to add each character to a temporary (initially empty) string until a space is encountered. At each instance of a space, the length of the temporary string is compared to the length of the "maxword" string, which is updated if it is found to be longer. The temporary string is emptied (reset to null using '\0') before proceeding to the next character in the input string.
#include <iostream>
#include <string>
using namespace std;
string LongestWord(string str) {
string tempstring;
string maxword;
int len = str.length();
for (int i = 0; i<=len; i++) {
if (tempstring.length()>maxword.length())
{
maxword=tempstring;
}
if (str[i]!=' ')
{
tempstring=tempstring+str[i];
}
else
{
tempstring='\0';
}
}
return maxword;
}
int main() {
cout << LongestWord(gets(stdin));
return 0;
}
#include <iostream>
using namespace std;
string longestWordInSentence(string str) {
// algorithm to count the number of words in the above string literal/ sentence
int words = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
words++;
}
}
// incrementing the words variable by one as the above algorithm does not take into account the last word, so we are incrementing
// it here manually just for the sake of cracking this problem
words += 1; // words = 5
// words would be the size of the array during initialization since this array appends only the words of the above string
// and not the spaces. So the size of the array would be equal to the number of words in the above sentence
string strWords[words];
// this algorithm appends individual words in the array strWords
short counter = 0;
for (short i = 0; i < str.length(); i++) {
strWords[counter] += str[i];
// incrementing the counter variable as the iterating variable i loops over a space character just so it does not count
// the space as well and appends it in the array
if (str[i] == ' ') {
counter++;
}
}
// algorithm to find the longest word in the strWords array
int sizeArray = sizeof(strWords) / sizeof(strWords[0]); // length of the strWords array
int longest = strWords[0].length(); // intializing a variable and setting it to the length of the first word in the strWords array
string longestWord = ""; // this will store the longest word in the above string
for (int i = 0; i < sizeArray; i++) { // looping over the strWords array
if (strWords[i].length() > longest) {
longest = strWords[i].length();
longestWord = strWords[i]; // updating the value of the longestWord variable with every loop iteration if the length of the proceeding word is greater than the length of the preceeding word
}
}
return longestWord; // return the longest word
}
int main() {
string x = "I love solving algorithms";
cout << longestWordInSentence(x);
return 0;
}
I have explained every line of the code in great detail. Please refer to the comments in front of every line of code. Here is a generalized approach:
Count the number of words in the given sentence
Initialize a string array and set the size of the array equal to the number of words in the sentence
Append the words of the given sentence to the array
Loop through the array and apply the algorithm of finding the longest word in the string. It is similar to finding the longest integer in an array of integers.
Return the longest word.
My original solution contained a bug: If you were to input 2 words of length n and 1 word of length n + k, then it would output those three words.
You should make a separate if condition to check whether the word length is the same as before, if yes, then you can append "; " and the other word.
This is what I would do:
Change if(counter > max_word) to if(counter >= max_word) so words of the same length are also taken into account.
Make the max string by default (so "" instead of " "). (See next point)
Add an if condition in the if(counter >= max_word)second if condition to see if the max string is not empty, and if it's not empty append "; "
Changing max = to max += so that it appends the words (in the second condition)
Wouldn't it be easier for you to split the whole line into a vector of string ?
Then you could ask the length of each element of the string and then print them. Because right now you still have all the words in a single string making each individual word hard to analyse.
It would also be hard, as you requested, to print all the words with the same length if you use a single string.
EDIT :
Start by looping through your whole input
Keep the greater length of word between the current one and the previously saved
Make a substring for each word and push_back it into a vector
Print the length of the bigger word
Loop through the vector and print each word of that size.
Look the following website for all references about vectors. dont forget to #include
www.cplusplus.com/reference/vector/vector/
#include <iostream>
#include <vector>
#include <string>
void LongestWord(std::string &str){
std::string workingWord = "";
std::string maxWord = "";
for (int i = 0; i < str.size(); i++){
if(str[i] != ' ')
workingWord += str[i];
else
workingWord = "";
if (workingWord.size() > maxWord.size())
maxWord = workingWord;
}
std::cout << maxWord;
}
int main(){
std::string str;
std::cout << "Enter a string:";
getline(std::cin, str);
LongestWord(str);
std::cout << std::endl;
return 0;
}
Source: http://www.cplusplus.com/forum/beginner/31169/
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
char ch;
int len,mlen=0;
getline(cin,s);
char* token=strtok(&s[0]," ");
string r;
while(token!=NULL)
{
r=token;
len=r.size();
if(mlen<len)
{
mlen=len;
a=token;
}
token = strtok(NULL, " ");
}
cout<<a;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
string str;
getline(cin,str);
cin.ignore();
int len =str.length();`
int current_len=0,max_len=0;
int initial=0,start=0;
int i=0;
while(1)
{
if(i==len+2)
{break;}
if(str[i]==' '|| i==len+1)
{
if(current_len>max_len)
{
initial=start;
max_len=current_len;
}
current_len=0;
start=i+1;
}
else
{
current_len++;
}
i++;
}
for (int i = 0; i < max_len; i++)
{
cout<<str[i+initial];
}
cout<<endl<<max_len<<endl;
return 0 ;
}

Reverse words of a sentence in c++, Asked on Google Code jam

How to solve this? https://code.google.com/codejam/contest/351101/dashboard#s=p1?
The code I ended up with is below, but it can only reverse strings up to one space because it was code keeping the literal logic in mind, Reverse the whole string, reverse the words, and done. The spaces are slightly messed up and when I tried a loop to detect number of spaces and act accordingly it failed. Please help! Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char revwrd[100];
char revstr[100];
string str;
getline(cin, str);
cout<<str;
int sps[10];
int len,y=0;
len = str.length();
cout<<"\n"<<"The Length of the string is:"<<len;
for(int x=len-1;x>-1;x--)
{
revstr[x] = str[y];
y++;
}
cout<<"\n"<<"The inverse of the string is:"<<"\n";
for(int z = 0;z<len;z++)
{
cout<<revstr[z];
}
cout<<"\n";
int no=0;
int spaces=0;
for(int a=0;a<len;a++)
{
if(revstr[a]== ' ')
{
sps[no]=a;
no++;
spaces++;
}
}
int rinc=0;
int spinc;
cout<<"\n";
spinc=sps[0];
int spinc2 = sps[0]+1;
int lend;
for(rinc=0;rinc<sps[0]+1;rinc++)
{
revwrd[rinc] = revstr[spinc];
spinc--;
}
for(lend=len;lend>sps[0];lend--)
{
revwrd[spinc2] = revstr[lend];
spinc2++;
}
cout<<"Spaces in the string:"<<spaces<<"\n";
cout<<"The words inversed are:"<<"\n";
for(int inc=1;inc<len+1;inc++)
{
cout<<revwrd[inc];
}
return 0;
}
The conditions of the challenge are that there is only a single space between words, and that spaces don't appear at the beginning or the end of the line, so for this particular exercise you don't have to worry about preserving spacing; as long as you write the output with a single space between each word, you're good.
With that in mind, you can read each word using regular formatted input:
std::string word;
...
while ( stream >> word )
// do something with word
You don't have to worry about buffer size, you don't have to worry about detecting spaces, etc. You do have to worry about detecting the newline character, but that's easily done using the peek method:
while ( stream >> word )
{
// do something with word;
if ( stream.peek() == '\n' )
break;
}
The above loop will read individual words from the input stream stream until it sees a newline character (there's probably a better way to do that, but it works).
Now, in order to reverse each line of input, you obviously need to store the strings somewhere as you read them. The easiest thing to do is store them to a vector:
std::vector< std::string > strings;
...
while ( stream >> word )
{
strings.push_back( word );
if ( stream.peek() == '\n' )
break;
}
So now you have a vector containing all the strings in the line, you just have to print them out in reverse order. You can use a reverse iterator to walk through the vector:
std::vector< std::string >::reverse_iterator it;
for ( it = strings.rbegin(); it != strings.rend(); ++it )
{
std::cout << *it << " ";
}
std::cout << std::endl;
The rbegin() method returns an iterator that points to the last element in the vector; the rend() method returns an iterator that points to an element before the first element of the vector; ++it advances the iterator to point to the next item in the vector, going back to front; and *it gives the string that the iterator points to. You can get a little more esoteric and use the copy template function:
std::copy( strings.rbegin(),
strings.rend(),
std::ostream_iterator<std::string>( std::cout, " " )
);
That single method call replaces the loop above. It creates a new ostream_iterator that will write strings to cout, separated by a single space character.
For the conditions of this particular exercise, this is more than adequate. If you were required to preserve spacing, or to account for punctuation or capitalization, then you'd have to do something a bit lower-level.
Just few loops and if's:
// Reverse Words
#include <iostream>
#include <string>
using namespace std;
int main() {
int tc; cin >> tc; cin.get();
for(int t = 0; t < tc; t++) {
string s, k; getline(cin, s);
for(int i = (s.length()- 1); i >= 0; i--) {
if(s[i] == ' ' || (i == 0)) {
if(i == 0) k += ' ';
for(int j = i; j < s.length(); j++) {
k += s[j];
if(s[j+1] == ' ' ) break;
}
}
}
cout << "Case #" << t + 1 << " " << k << endl;
}
return 0;
}
This might handle multi spaces:
std::string ReverseSentence(std::string in)
{
std::vector<string> words;
std::string temp = "";
bool isSpace = false;
for(int i=0; in.size(); i++)
{
if(in[i]!=' ')
{
if(isSpace)
{
words.push_back(temp);
temp = "";
isSpace = false;
}
temp+=in[i];
}
else
{
if(!isSpace)
{
words.push_back(temp);
temp = "";
isSpace = true;
}
temp += " ";
}
}
std::reverse(words.begin(),words.end());
std::string out = "";
for(int i=0; i<words.size(); i++)
{
out+=words[i];
}
return out;
}
you can follow this method :
step 1 : just check for spaces in input array store their index number in an integer array.
step 2 : now iterate through this integer array from end
step a : make a string by copying characters from this index to previous index .
note : since for first element there is no previous element in that case you will copy from this index to end of the input string .
step b : step a will give you a word from end of input string now add these word with a space to make your output string .
I hope this will help you .
This problem is really made for recursion:
void reverse()
{
string str;
cin >> str;
if (cin.peek() != '\n' || cin.eof()) {
str = " " + str;
reverse();
}
cout << str;
}
int main(int argc, const char * argv[])
{
int count = 0;
cin >> count;
for (int i = 0; i < count; i++) {
cout << "Case #" << (i + 1) << ": ";
reverse();
cout << endl;
}
return 0;
}
So I read word by word and add one space in front of the word until end of line or file is reached. Once end of line is reached the recursion unwraps and prints the read strings in reversed order.
I went for the brute force, and I badly wanted to use pointers!
get the sentence
detect every word and put them in a container.
read backwards the container.
This is it:
#include <iostream>
#include <string>
#include <vector>
int main()
{
char *s1 = new char[100];
std::cin.getline(s1, 100);
std::vector<std::string> container;
char* temp = new char[100];
char *p1, *p0;
p1 =p0 = s1;
int i;
do{
if (*p1==' ' || *p1=='\0'){
//std::cout<<p1-p0<<' ';
for(i=0;i<p1-p0;++i) temp[i]=p0[i]; temp[i]='\0';
p0 = p1+1;
container.push_back(temp);
std::cout<<temp;
}
p1++;
}while(*(p1-1)!='\0');
std::cout<<std::endl;
for(int i=container.size()-1;i>=0;i--) std::cout<<container[i]<<' ';
return 0;
}

Max Repeated Word in a string

I was trying to do a very common interview problem "Finding the max repeated word in a string " and could not find much resources in net for c/c++ implementation. So I coded it myself here.
I have tried to do most of the coding from scratch for better understanding.
Could you review my code and provide comments on my algorithm. Some people have suggested using hashtables for storing the count, but am not using hashtables here.
#include<stdafx.h>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
string word[10];
//splitting string into words
int parsestr(string str)
{
int index = 0;
int i = 0;
int maxlength = str.length();
int wordcnt = 0;
while(i < maxlength)
{
if(str[i]!= ' ')
{
word[index] = word[index]+str[i];
}
else
{
index++;//new word
wordcnt = index;
}
i++;
}
return wordcnt;
}
//find the max word count out of the array and return the word corresponding to that index.
string maxrepeatedWord(int wordcntArr[],int count)
{
int max = 0;
int index = 0;
for(int i=0;i<=count;i++)
{
if(wordcntArr[i] > max)
{
max = wordcntArr[i];
index = i;
}
}
return word[index];
}
void countwords(int count)
{
int wordcnt = 0;
int wordcntArr[10];
string maxrepeatedword;
for(int i=0;i<=count ;i++)
{
for(int j=0;j<=count;j++)
{
if(word[i]==word[j])
{
wordcnt++;
//word[j] = "";
}
else
{}
}
cout<<" word "<< word[i] <<" occurs "<< wordcnt <<" times "<<endl;
wordcntArr[i] = wordcnt;
wordcnt = 0;
}
maxrepeatedword = maxrepeatedWord(wordcntArr,count);
cout<< " Max Repeated Word is " << maxrepeatedword;
}
int main()
{
string str = "I am am am good good";
int wordcount = 0;
wordcount = parsestr(str);
countwords(wordcount);
}
Just for the sake of comparison, the most obvious way to do this is C++ is:
#include <map>
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::istringstream input("I am am am good good");
std::map<std::string, int> count;
std::string word;
decltype(count)::const_iterator most_common;
while (input >> word)
{
auto iterator = count.emplace(word, 0).first;
++iterator->second;
if (count.size() == 1 ||
iterator->second > most_common->second)
most_common = iterator;
}
std::cout << '\"' << most_common->first << "' repeated "
<< most_common->second << " times\n";
}
See it run here.
Notes:
map::emplace returns a pair<iterator,bool> indicating where the word & its count are in the map, and whether its newly inserted. We only care about where so capture emplace(...).first.
As we update the count, we check if that makes the word the most-common word seen so far. If so we copy the iterator to the local variable most_common, so we have a record of both the most commonly seen word so far and its count.
Some things you're doing that are worth thinking about:
word is a global variable - it's a good habit to pass things as function arguments unless it's terribly inconvenient, means the code can be reused more easily from async signal handlers or other threads, and it's more obvious in looking at a function call site what the inputs and outputs might be. As is, the call countwords(wordcount) makes it look like countwords' only input is the int wordcount.
fixed sized arrays: if you've more than 10 words, you're sunk. C++ Standard containers can grow on demand.
there are a few convenience functions you could use, such as std::string::operator+=(char) to append a char more concisely ala my_string += my_char;
Generally though, your code is quite sensible and shows a good understanding of iteration and problem solving, doing it all very low-level but that's good stuff to understand in a very hands-on way.
Code Snippet :
void mostRepeat(string words[], int n)
{
int hash[n]={0};
for(int j=0; j<n; j++)
{
for(int i=0; i<n; i++)
{
if(words[j]==words[i]) hash[j]++;
}
}
int maxi = hash[0];
int index = 0;
for(int i=0; i<n; i++)
{
if(maxi<hash[i])
{
maxi=hash[i];
index = i;
}
}
cout<<words[index]<<endl;
}
Full program : Link
import java.util.*;
public class StringWordDuplicates {
static void duplicate(String inputString){
HashMap<String, Integer> wordCount = new HashMap<String,Integer>();
String[] words = inputString.split(" ");
for(String word : words){
if(wordCount.containsKey(word)){
wordCount.put(word, wordCount.get(word)+1);
}
else{
wordCount.put(word, 1);
}
}
//Extracting of all keys of word count
Set<String> wordsInString = wordCount.keySet();
for(String word : wordsInString){
if(wordCount.get(word)>1){
System.out.println(word+":"+wordCount.get(word));
}
}
}
public static void main(String args[]){
duplicate("I am Java Programmer and IT Server Programmer with Java as Best Java lover");
}
}