Fastest way to count words of string - c++

How could I make this algorithm faster and shorten this code which counts word of given string?
int number_of_words(std::string &s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
// skip spaces
while (s[i] == ' ' && i < s.length())
i++;
if (i == s.length())
break;
// word found
count++;
// inside word
while (s[i] != ' ' && i < s.length())
i++;
}
return count;
}

Your code is quite alright, speed-wise. But if you want to make your code shorter, you may use find_first_not_of() and find_first_of standard functions, like I did in following code that solves your task.
I made an assumption that all your words are separated by only spaces. If other separators are needed you may pass something like " \r\n\t" instead of ' ' in both lines of my code.
One small optimization that can be made in your code is when you notice that after first while-loop we're located on non-space character, so we can add ++i; line for free before second loop. Similarly after second while-loop we're located on space character so we may add one more ++i; line after second while loop. This will give a tiny bit of speed gain to avoid extra two checks inside while loop.
Try it online
#include <iostream>
#include <string>
int number_of_words(std::string const & s) {
ptrdiff_t cnt = 0, pos = -1;
while (true) {
if ((pos = s.find_first_not_of(' ', pos + 1)) == s.npos) break;
++cnt;
if ((pos = s.find_first_of(' ', pos + 1)) == s.npos) break;
}
return cnt;
}
int main() {
std::cout << number_of_words(" abc def ghi ") << std::endl;
}
Output:
3

Related

How to get the number of words from a line from a text file

I am trying to get the number of words from a line in a text file. I used .getline() in order to extract a line from the entire text file. The code is:
#include <iostream>
#include <iomanip>
#include <fstream>
int main()
{
char const* filename = "duck.txt";
std::ifstream ifs{ filename };
constexpr size_t MAX_LINE_LEN{ 2048 };
char line[MAX_LINE_LEN];
int lineCount = 0;
int totalWordCount = 0;
int totalByteCount = 0;
while (ifs.getline(line, MAX_LINE_LEN-1))
{
int lineWord = 0;
char* q = &line[0];
if (ifs.eof())
{
lineCount--;
totalByteCount--;
}
while (*q != '\0')
{
q++;
totalByteCount++;
}
totalByteCount++;
if (*q == '\0')
{
lineCount++;
}
int i = 0;
int j = 0;
while (line[i] != '\0' && line[j] != '\0')
{
while (line[i] == ' ')
{
i++;
}
j = i;
while (line[j] != ' ')
{
j++;
}
lineWord++;
j = i;
}
totalWordCount += lineWord;
}
std::cout << "Total Lines: " << lineCount << '\n' << "Total Words: " << totalWordCount << '\n' << "Total Bytes: " << totalByteCount;
}
But the only important part is:
int i = 0;
int j = 0;
while (line[i] != '\0' && line[j] != '\0')
{
while (line[i] == ' ')
{
i++;
}
j = i;
while (line[j] != ' ')
{
j++;
}
lineWord++;
j = i;
}
totalWordCount += lineWord;
I'm trying to read the line character by character until I reach a non-whitespace character after which I'll assign that subscript to i. Then, I'll set j to the subscript of the first whitespace encountered after the character of line[i]. If j finds a whitespace, then there is a word. If j reaches '\0', then the line has ended and I end the while loop. When I try to compile and run this, the compiler just displays nothing. What am I doing wrong? Also, I can't add anymore header files
In your original code:
int i = 0;
int j = 0;
while (line[i] != '\0' && line[j] != '\0')
{
while (line[i] == ' ') // you do not check for end of string character?
{
i++;
}
j = i; // here i = j = beginning of word.
// since you rewind to beginning of the word below,
// your program keeps repeating this loop endlessly
while (line[j] != ' ') // this loop could easily run for quite a while.
// until it seg-faults
{
j++;
}
lineWord++;
j = i; // BUG Here! you're 'rewinding' j to to beginning of the word.
// you loop back and keep counting the same word over and over.
}
totalWordCount += lineWord;
What is the purpose of i and j ? Wouldn't the code be simpler and easier to read and maintain using a single pointer? Or a single index? This kind of algorithm is where a pointer would excel, though, as the only arithmetic pointer operation needed is increment.
As in:
const char* p = &line[0];
int word_count = 0;
line[MAX_LINE_LEN - 1] = 0; // making sure the code below stays within boundaries.
for(;;)
{
// skip to next word
while (*p && *p == ' ') ++p; // stay within the string by testing for zero.
if (!*p)
break; // done!
// since p now points to the beginning of a word, we've got one
++word_count;
// skip to end of word
while (*p && *p != ' ') ++p;
}
This is all fine, for most cases but there could be some exceptional typos in the text, like "hello, world !", where the last punctuation would be counted as a word. There is also the problem of horizontal tabs, which could also be counted erroneously as words.
To cover these cases, you should test for valid characters for words, instead of for space, which is a rather vague concept.
Without using library calls, You'd need to define what constitutes spaces and punctuation, either with a constant, or with a function.
Substituting the test for space with a more targeted test, using isalnum() to check for alpha or numeric characters:
for(;;)
{
// skip to next word
while (*p && !std::isalnum(*p & 0xFF)) ++p;
if (!*p)
break; // done!
++word_count;
// skip to end of word
while (*p && std::isalnum(*p & 0xFF)) ++p;
}
Beware of function of the isalnum(), isalpha().. family, they define their input as an int, the mask ensures that characters in the 128-255 range are not sign-extended aand are passed correctly as positive values.

How to fill an array with a sentence?

For instance i have the sentence " I am Piet". I want to fill this sentence into an array in a way that I[0], am[1] Piet[2]. Below is the code i've made. The problem is that the sentence is filled in each element of the array.
#include <iostream>
#include <string>
using namespace std;
// function to populate my array
void populateMyArray(string*myArray, string sentence, int size)
{
for (int i = 0; i < size; i++)
{
*myArray = sentence;
myArray++;
}
}
// function to count works in the sentence
int countWords(string x)
{
int Num = 0;
char prev = ' ';
for (unsigned int i = 0; i < x.size(); i++) {
if (x[i] != ' ' && prev == ' ') Num++;
prev = x[i];
}
return Num;
}
int main()
{
string sentence1;
cout << "Please enter a line of text:\n";
getline(cin, sentence1);
int nWords1 = countWords(sentence1);
string *arr1 = new string[nWords1];
populateMyArray(arr1, sentence1, nWords1); //populate array1
for (int i = 0; i < nWords1; i++)
{
cout << "sentence one: " << arr1[i] << "\n";
}
system("PAUSE");
}
You can use vector in order to save data and each time you should use space between two words and you will store each string type into vector array
#include<bits/stdc++.h>
using namespace std;
main()
{
string s;
getline(cin,s);
vector<string> ss;
string temp = "";
s +=" ";
for(int i = 0 ; i < s.size();i ++){
if(s[i] != ' ')
temp += s[i];
else{
ss.push_back(temp);
temp = "";
}
}
for(int i = 0 ; i < ss.size();i ++)
cout << ss[i] <<" ";
}
Instead of using an array, use a std::vector instead. This way you don't have to worry about variable word sizes or overflowing anything in case a word or sentence is too long. Rather you can just do something like this:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
// Get all words on one line
std::cout << "Enter words: " << std::flush;
std::string sentence;
getline(std::cin, sentence);
// Parse words into a vector
std::vector<std::string> words;
std::string word;
std::istringstream iss(sentence);
while( iss >> word ) {
words.push_back(word);
}
// Test it out.
for(auto const& w : words) {
std::cout << w << std::endl;
}
}
For an example sentence of I like cats and dogs equally you will have: words[0] = I, words[1] = like and so on.
If I understood correctly you are trying to split the input sentence into words.
You could do it like this:
void populateMyArray(string *myArray, string sentence, int size)
{
int firstCharIndex = -1;
char prev = ' ';
for (unsigned int i = 0; i < sentence.size(); i++) {
// Find the first character index of current word
if (sentence[i] != ' ' && prev == ' ') {
firstCharIndex = i;
}
// Check if it's the end of current word
// and get substring from first to last index of current word
else if (sentence[i] == ' ' && prev != ' ') {
*myArray = sentence.substr(firstCharIndex, i - firstCharIndex);
myArray++;
}
prev = sentence[i];
}
// For the last word
if (firstCharIndex != -1 && sentence[sentence.size() - 1] != ' ') {
*myArray = sentence.substr(firstCharIndex, sentence.size() - firstCharIndex);
}
}
How to think like a programmer.
The first thing we need is definitions of the beginning or a word and the end of a word. You might think that the beginning of a word is a non-space preceded by a space and the end of a word is a non-space followed by a space. But those definitions are wrong because they ignore the possibility of words at the start or end of the string. The correct definition of the beginning of a word is a non-space at the start of the string or a non-space preceded by a space. Similarly the end of a word is a non-space at the end of the string or a non-space followed by a space.
Now we have the definitions we capture them in two functions. It's very important to break complex problems down into smallier pieces and the way to do that is by writing functions (or classes).
bool beginning_of_word(string str, int index)
{
return str[index] != ' ' && (index == 0 || str[index - 1] == ' ');
}
bool end_of_word(string str, int index)
{
return str[index] != ' ' && (index == str.size() - 1 || str[index + 1] == ' ');
}
Now we're getting closer, but we still need the idea of finding the next start of word, or the next end of word, so we can loop through the sentence finding each word one at a time. Here are two functions for finding the next start and next end of word. They start from a given index and find the next index that is the start or end of a word. If no such index is found they return -1.
int next_beginning_of_word(string str, int index)
{
++index;
while (index < str.size())
{
if (beginning_of_word(str, index))
return index; // index is a start of word so return it
++index;
}
return -1; // no next word found
}
int next_end_of_word(string str, int index)
{
++index;
while (index < str.size())
{
if (end_of_word(str, index))
return index; // index is an end of word so return it
++index;
}
return -1; // no next word found
}
Now we have a way of looping through the words in a sentence we're ready to write the main loop. We use substr to break the words out of the sentence, substr takes two parameters the index of the start of the word and the length of the word. We can get the length of the word by substracting the start from the end and adding one.
int populateMyArray(string* array, string sentence)
{
// find the first word
int start = next_beginning_of_word(sentence, -1);
int end = next_end_of_word(sentence, -1);
int count = 0;
while (start >= 0) // did we find it?
{
// add to array
array[count] = sentence.substr(start, end - start + 1);
++count;
// find the next word
start = next_beginning_of_word(sentence, start);
end = next_end_of_word(sentence, end);
}
return count;
}
Now for extra credit we can rewrite countWords using next_beginning_of_word
int countWords(string sentence)
{
int start = next_beginning_of_word(sentence, -1);
int count = 0;
while (start >= 0)
{
++count;
start = next_beginning_of_word(sentence, start);
}
return count;
}
Notice the similarity of the countWords and the populateMyArray functions, the loops are very similar. That should give you confidence.
This is the way programmers work, when you have a problem that is too complex for you to handle, break it down into smaller pieces.

Counting words in a string

I am learning C++ on my own. I have written this program to count the number of words in a string. I know it's not the best way to do this, but this was what I could think of.
I am using spaces to count the number of words. Here is the problem.
countWords(""); // ok, 'x.empty()' identifies it as an empty string.
countWords(" "); // 'x.empty()' fails, function returns 1.
p.s I want this program to not count symbols like, "!","?" as words. Here is my code:
#include <iostream>
#include <string>
int countWords(std::string x);
int main() {
std::cout << countWords("Hello world!");
}
int countWords(std::string x) {
if(x.empty()) return 0; // if the string is empty
int Num = 1;
for(unsigned int i = 0; i < x.size(); i++) {
// if there is a space in the start
if(x[0] == ' ') continue;
// second condition makes sure that i don't count 2 spaces as 2 words
else if(x[i] == ' ' && x[i - 1] != ' ') Num++;
}
return Num;
}
Your function can be reduced to this:
int countWords(std::string x) {
int Num = 0;
char prev = ' ';
for(unsigned int i = 0; i < x.size(); i++) {
if(x[i] != ' ' && prev == ' ') Num++;
prev = x[i];
}
return Num;
}
Here is a demo
Edit: To follow up comment:
Here is a simple way to replace other characters with ' ', thought there might be a build method for this:
void replace(std::string &s, char replacer, std::set<char> &replacies)
{
for (int i=0; i < s.size(); i++)
if (replacies.count(s[i])) s[i] = replacer;
}
demo
The problem with your answer is that you are counting the number of words after which there is a ' ' sign. I believe you start with Num = 1 because you won't be counting the last word. Hovewer that only occurs when the string youre analysing does not end with ' '. Otherwise you will have 1 more word counted. The easiest way to fix this is to add
if(x.back() == ' ')
Num--;
right before returning the answer.
Your solution is insufficient. It will fail when applied with:
Leading spaces
Trailing spaces
Only spaces
Other forms of whitespace
You need to rethink how your algorithm should work as you simply need a more sophisticated method to cover all the use cases.
Or you could avoid reinventing the wheel and use what the standard library already provides, e.g.:
int countWords(const std::string& s) {
std::istringstream iss{s};
return std::distance(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{});
}
Here std::istringstream and std::istream_iterator is used to tokenize the string, and std::distance is used to get the number of tokens extracted.
I found the best using string stream:
int Count(const std::string &string)
{
stringstream ss(string);
char cmd[256] = {0};
int Words = 0;
while(true)
{
ss >> cmd;
if(!ss)
break;
Words++;
}
return Words;
Input: " Hello my dear friend "
Output: 4
It will not fail even if appiled with:
Leading spaces
Trailing spaces
Only spaces
Other forms of whitespace
So I tried on my own, after reading some useful comments. Here is my solution. I have checked my program for worst case scenario. If any of you, can find any cases for which this program doesn't work, let me know, so that I can work and improve it.
And just to be clear, we don't want symbols like, "," , "!" , "?", "." , "\n" to be counted as words. But obviously, "I" should be counted as word, as we consider it in the language. I have made sure of all this by replacing them with spaces. Let me know if I missed something.
#include <iostream>
#include <string>
void replace(std::string& str, char x, char y);
int countWords(std::string x);
int main(){
std::cout<<countWords(" \n \t Hello, world ! ");
}
void replace(std::string& str, char x, char y){
for(unsigned int i=0;i<str.size();i++){
if(str[i]==x) str[i]=y;
}
}
int countWords(std::string x){
replace(x,',',' ');
replace(x,'.',' ');
replace(x,'!',' ');
replace(x,'?',' ');
replace(x,'(',' ');
replace(x,')',' ');
replace(x,'\n',' ');
replace(x,'\t',' ');
replace(x,'"',' ');
if(x.empty()) return 0;
int Num=1;
for(unsigned int i=1;i<x.size();i++){
if(x[i]==' ' && x[i-1]!=' ') Num++;
}
if(x.back() == ' ') Num--;
return Num;
}
This is simple and fast on my machine. It iterates over the string, using a bool to track
whether it's inside a word or not, and whitespace characters as word delimiters. I tested with the isspace() library function but this switch statement was slightly faster.
int countwords(const std::string &str)
{
int count = 0;
bool in_word = false;
for (char ch : str) {
switch (ch) {
case '\t': case '\n': case '\v': case '\f': case '\r': case ' ':
in_word = false;
break;
default:
if (!in_word) {
in_word = true;
++count;
}
break;
}
}
return count;
}
This is easy to extend or modify for different word delimiters. Here is a version that considers any non-alphabetical character as a delimiter. Changing the !isalpha() call to isspace() will give the same results as the code above.
int countwords(const std::string &str)
{
int count = 0;
bool in_word = false;
for (char ch : str) {
if (!isalpha(ch)) { // non-alpha chars are word delimiters
in_word = false;
} else if (!in_word) {
in_word = true;
++count;
}
}
return count;
}
int countwords(std::string x)
{
int i, count = 0;
for (i = 0; i < x.size(); i++)
if (x[i] == ' ')
count++; //just count empty spaces
count++; //count++ is same as count+1,so there will be count+1 words in string
if (x.size() == 0)
count = 0;
return count;
}
Add the following lines to the code
int Num;
if(x[0] == ' ') Num = 0;
else Num = 1;
this would eliminate the count of a blank in the start of the string
#include <iostream>
#include <string>
int countWords(std::string x);
int main() {
std::cout << countWords("Hello world!");
}
int countWords(std::string x) {
if(x.empty()) return 0; // if the string is empty
int Num;
if(x[0] == ' ') Num = 0;
else Num = 1;
for(unsigned int i = 0; i < x.size(); i++) {
// if there is a space in the start
if(x[0] == ' ') continue;
// second condition makes sure that i don't count 2 spaces as 2 words
else if(x[i] == ' ' && x[i - 1] != ' ') Num++;
}
return Num;
}

Remove multiple spaces [duplicate]

This is an interview question
Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.
input = "I Like StackOverflow a lot"
output = "I Like StackOverflow a lot"
String functions are not allowed, as this is an interview question. Looking for an algorithmic solution of the problem.
Does using <algorithm> qualify as "algorithmic solution"?
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
struct BothAre
{
char c;
BothAre(char r) : c(r) {}
bool operator()(char l, char r) const
{
return r == c && l == c;
}
};
int main()
{
std::string str = "I Like StackOverflow a lot";
std::string::iterator i = unique(str.begin(), str.end(), BothAre(' '));
std::copy(str.begin(), i, std::ostream_iterator<char>(std::cout, ""));
std::cout << '\n';
}
test run: https://ideone.com/ITqxB
A c++0x - solution using a lambda instead of a regular function object. Compare to Cubbi's solution.
#include <string>
#include <algorithm>
int main()
{
std::string str = "I Like StackOverflow a lot";
str.erase(std::unique(str.begin(), str.end(),
[](char a, char b) { return a == ' ' && b == ' '; } ), str.end() );
}
Keep two indices: The next available spot to put a letter in (say, i), and the current index you're examining (say, j).
Just loop over all the characters with j, and whenever you see a letter, copy it to index i, then increment i. If you see a space that was not preceded by a space, also copy the space.
I think this would work in-place...
I'd just go with this:
int main(int argc, char* argv[])
{
char *f, *b, arr[] = " This is a test. ";
f = b = arr;
if (f) do
{
while(*f == ' ' && *(f+1) == ' ') f++;
} while (*b++ = *f++);
printf("%s", arr);
return 0;
}
I'd propose a little state machine (just a simple switch statement). Because if the interviewer is anything like me, the first enhancement they'll ask you to do is to fully trim any leading or trailing spaces, so that:
" leading and trailing "
gets transformed to:
"leading and trailing"
instead of:
" leading and trailing "
This is a really simple modification to a state-machine design, and to me it seems easier to understand the state-machine logic in general over a 'straight-forward' coded loop, even if it takes a few more lines of code than a straight-forward loop.
And if you argue that the modifications to the straight forward loop wouldn't be too bad (which can be reasonably argued), then I (as the interviewer) would throw in that I also want leading zeros from numbers to be be trimmed.
On the other hand, a lot of interviewers might actually dislike a state-machine solution as being 'non-optimal'. I guess it depends on what you're trying to optimize.
Here it is using only stdio:
#include <stdio.h>
int main(void){
char str[] = "I Like StackOverflow a lot";
int i, j = 0, lastSpace = 0;
for(i = 0;str[i]; i++){
if(!lastSpace || str[i] != ' '){
str[j] = str[i];
j++;
}
lastSpace = (str[i] == ' ');
}
str[j] = 0;
puts(str);
return 0;
}
Trimming multiple spaces also means a space should always be followed by a non space character.
int pack = 0;
char str[] = "I Like StackOverflow a lot";
for (int iter = 1; iter < strlen(str); iter++)
{
if (str[pack] == ' ' && str[iter] == ' ')
continue;
str[++pack] = str[iter];
}
str[++pack] = NULL;
int j = 0;
int k=0;
char str[] = "I Like StackOverflow a lot";
int length = strlen(str);
char str2[38];
for (int i = 0; i < length; i++)
{
if (str[i] == ' ' && str[i+1] == ' ')
continue;
str2[j] = str[i];
j++;
}
str2[j] =NULL;
cout<<str2;
void trimspaces(char * str){
int i = 0;
while(str[i]!='\0'){
if(str[i]==' '){
for(int j = i + 1; j<strlen(str);j++){
if(str[j]!=' '){
memmove(str + i + 1, str + j, strlen(str)-j+1);
break;
}
}
}
i++;
}
}
Functional variant in Haskell:
import Data.List (intercalate)
trimSpaces :: String -> String
trimSpaces = intercalate " " . words
The algorithm the next:
breaks a string up into a list of words, which were delimited by white space
concatenate the list inserting one space between each element in list
This is a very simple implementation of removing extra whitespaces.
#include <iostream>
std::string trimExtraWhiteSpaces(std::string &str);
int main(){
std::string str = " Apple is a fruit and I like it . ";
str = trimExtraWhiteSpaces(str);
std::cout<<str;
}
std::string trimExtraWhiteSpaces(std::string &str){
std::string s;
bool first = true;
bool space = false;
std::string::iterator iter;
for(iter = str.begin(); iter != str.end(); ++iter){
if(*iter == ' '){
if(first == false){
space = true;
}
}else{
if(*iter != ',' && *iter != '.'){
if(space){
s.push_back(' ');
}
}
s.push_back(*iter);
space = false;
first = false;
}
}
return s;
}
std::string tripString(std::string str) {
std::string result = "";
unsigned previous = 0;
if (str[0] != ' ')
result += str[0];
for (unsigned i = 1; i < str.length()-1; i++) {
if (str[i] == ' ' && str[previous] != ' ')
result += ' ';
else if (str[i] != ' ')
result += str[i];
previous++;
}
if (str[str.length()-1] != ' ')
result += str[str.length()-1];
return result;
}
This may be an implementation of the accepted idea.

Interview Question : Trim multiple consecutive spaces from a string

This is an interview question
Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.
input = "I Like StackOverflow a lot"
output = "I Like StackOverflow a lot"
String functions are not allowed, as this is an interview question. Looking for an algorithmic solution of the problem.
Does using <algorithm> qualify as "algorithmic solution"?
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
struct BothAre
{
char c;
BothAre(char r) : c(r) {}
bool operator()(char l, char r) const
{
return r == c && l == c;
}
};
int main()
{
std::string str = "I Like StackOverflow a lot";
std::string::iterator i = unique(str.begin(), str.end(), BothAre(' '));
std::copy(str.begin(), i, std::ostream_iterator<char>(std::cout, ""));
std::cout << '\n';
}
test run: https://ideone.com/ITqxB
A c++0x - solution using a lambda instead of a regular function object. Compare to Cubbi's solution.
#include <string>
#include <algorithm>
int main()
{
std::string str = "I Like StackOverflow a lot";
str.erase(std::unique(str.begin(), str.end(),
[](char a, char b) { return a == ' ' && b == ' '; } ), str.end() );
}
Keep two indices: The next available spot to put a letter in (say, i), and the current index you're examining (say, j).
Just loop over all the characters with j, and whenever you see a letter, copy it to index i, then increment i. If you see a space that was not preceded by a space, also copy the space.
I think this would work in-place...
I'd just go with this:
int main(int argc, char* argv[])
{
char *f, *b, arr[] = " This is a test. ";
f = b = arr;
if (f) do
{
while(*f == ' ' && *(f+1) == ' ') f++;
} while (*b++ = *f++);
printf("%s", arr);
return 0;
}
I'd propose a little state machine (just a simple switch statement). Because if the interviewer is anything like me, the first enhancement they'll ask you to do is to fully trim any leading or trailing spaces, so that:
" leading and trailing "
gets transformed to:
"leading and trailing"
instead of:
" leading and trailing "
This is a really simple modification to a state-machine design, and to me it seems easier to understand the state-machine logic in general over a 'straight-forward' coded loop, even if it takes a few more lines of code than a straight-forward loop.
And if you argue that the modifications to the straight forward loop wouldn't be too bad (which can be reasonably argued), then I (as the interviewer) would throw in that I also want leading zeros from numbers to be be trimmed.
On the other hand, a lot of interviewers might actually dislike a state-machine solution as being 'non-optimal'. I guess it depends on what you're trying to optimize.
Here it is using only stdio:
#include <stdio.h>
int main(void){
char str[] = "I Like StackOverflow a lot";
int i, j = 0, lastSpace = 0;
for(i = 0;str[i]; i++){
if(!lastSpace || str[i] != ' '){
str[j] = str[i];
j++;
}
lastSpace = (str[i] == ' ');
}
str[j] = 0;
puts(str);
return 0;
}
Trimming multiple spaces also means a space should always be followed by a non space character.
int pack = 0;
char str[] = "I Like StackOverflow a lot";
for (int iter = 1; iter < strlen(str); iter++)
{
if (str[pack] == ' ' && str[iter] == ' ')
continue;
str[++pack] = str[iter];
}
str[++pack] = NULL;
int j = 0;
int k=0;
char str[] = "I Like StackOverflow a lot";
int length = strlen(str);
char str2[38];
for (int i = 0; i < length; i++)
{
if (str[i] == ' ' && str[i+1] == ' ')
continue;
str2[j] = str[i];
j++;
}
str2[j] =NULL;
cout<<str2;
void trimspaces(char * str){
int i = 0;
while(str[i]!='\0'){
if(str[i]==' '){
for(int j = i + 1; j<strlen(str);j++){
if(str[j]!=' '){
memmove(str + i + 1, str + j, strlen(str)-j+1);
break;
}
}
}
i++;
}
}
Functional variant in Haskell:
import Data.List (intercalate)
trimSpaces :: String -> String
trimSpaces = intercalate " " . words
The algorithm the next:
breaks a string up into a list of words, which were delimited by white space
concatenate the list inserting one space between each element in list
This is a very simple implementation of removing extra whitespaces.
#include <iostream>
std::string trimExtraWhiteSpaces(std::string &str);
int main(){
std::string str = " Apple is a fruit and I like it . ";
str = trimExtraWhiteSpaces(str);
std::cout<<str;
}
std::string trimExtraWhiteSpaces(std::string &str){
std::string s;
bool first = true;
bool space = false;
std::string::iterator iter;
for(iter = str.begin(); iter != str.end(); ++iter){
if(*iter == ' '){
if(first == false){
space = true;
}
}else{
if(*iter != ',' && *iter != '.'){
if(space){
s.push_back(' ');
}
}
s.push_back(*iter);
space = false;
first = false;
}
}
return s;
}
std::string tripString(std::string str) {
std::string result = "";
unsigned previous = 0;
if (str[0] != ' ')
result += str[0];
for (unsigned i = 1; i < str.length()-1; i++) {
if (str[i] == ' ' && str[previous] != ' ')
result += ' ';
else if (str[i] != ' ')
result += str[i];
previous++;
}
if (str[str.length()-1] != ' ')
result += str[str.length()-1];
return result;
}
This may be an implementation of the accepted idea.