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;
}
Related
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
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.
I'm figuring out the algorithm on this function and it keeps crashing at runtime, here's the code snippet:
int wordCounter(char usStr[]) {
int index= 0, punct= 0;
while(usStr[index]!= '\0') //If it's not the end of the sentence
if(usStr[index]== ' ') //If it finds a space
index++;
while(usStr[index]== '\0') //If it's the end of the sentence.
punct++;
int allChar= punct+ index;
return allChar;
}
I shall post the full program if need arises, but for now I need someone to help me crack down the source of the problem.
UPDATE: Here's my int main. Assume numWords is a function that accepts a string class object as its argument and asks the user for input:
int main()
{
string userVal;
numWords(userVal);
char *conStr= new char[' ']; //I'm very doubtful and worried about the contents insing the [].
strcpy(conStr, userVal.c_str()); //String converted to a C-string.
int fin= wordCounter(conStr);
cout<< "The number of words in the sentence is "<< fin<< "."<< endl;
pause();
return 0;
}
Though I have no idea what you're really asking for, I think you should have a condition to end your 1st while() loop to adjust at beginning of words:
int wordCounter(char usStr[]) {
int index= 0, punct= 0;
while(usStr[index]!= '\0') { // <<< Use effin' braces
if(usStr[index]== ' ') { // <<< Use effin' braces
index++;
}
else {
break;
}
}
// index points to a non ' ' character or '\0' here
// No idea, what you're trying to achieve with the following lines
// of code.
while(usStr[index] == '\0') { // If it's the end of the sentence ...
// ... this part loops forever!
punct++;
}
int allChar = punct + index;
return allChar;
}
Simple array way:
int wordCounter(char usStr[])
{
int wordcount = 0;
int charcount = 0;
int index = 0;
while (usStr[index] != '\0')
{
if (usStr[index] == ' ')
{
if (charcount)
{ //only count non-empty tokens
wordcount++;
charcount = 0;
}
}
else
{
charcount++;
}
index++;
}
if (charcount)
{ // get last word, if any.
wordcount++;
}
return wordcount;
}
Simple C++ way:
int wordCounter(char usStr[])
{
int wordcount = 0;
std::stringstream stream(usStr);
std::string temp;
while (stream >> temp)
{ // got a token
wordcount++;
}
return wordcount;
}
Breakdown of what went wrong:
while(usStr[index]!= '\0') //good
if(usStr[index]== ' ') //good
index++; //bad
Lets look at a simple case "Hi!"
Iteration 1:
index = 0, usStr[index] = H
while(usStr[index]!= '\0')
H != '\0', enter
if(usStr[index]== ' ') //good
H != ' ', do not enter. Do not increment index
Iteration 2:
index = 0, usStr[index] = H
while(usStr[index]!= '\0')
H != '\0', enter
if(usStr[index]== ' ') //good
H != ' ', do not enter. Do not increment index
Iteration 3:
index = 0, usStr[index] = H
while(usStr[index]!= '\0')
H != '\0', enter
if(usStr[index]== ' ') //good
H != ' ', do not enter. Do not increment index
See the problem yet? If not, I can cut and past all night. Rather get some food and sleep, though.
int wordCounter(char usStr[]) {
int index= sizeof(usStr);
int result = 0;
for (int i=0; i<index; i++){
if(usStr[index]== ' ')
result++;
}//end of the loop
return result+1;
} //try this one.
Be warned, I'm a beginner. Sorry, I feel like I have to say that in case I'm totally wrong. :) Hopefully I won't have to say that for too long.
Anyways, I would do this in the simplest way I can come up with. Instead of a char array, I would just use a std::string. Here's a little function I made, which is derived from a function I made to split std::strings into substrings.
// split the string s into substrings and count the number of substrings
int count_substrings(const string& s)
{
int count{ 0 };
stringstream ss{ s };
for (string buffer; ss >> buffer;)
++count;
return count;
}
So what this does is it takes the string and stores it into a stringstream. Then the "ss >> buffer" will go through the characters in the string and when it hits whitespace, it'll store that substring into "buffer" and go into the for loop, which increments "count". It goes into the for loop each time it finds a substring, which is how it counts the number of substrings. Notice that "buffer" isn't actually being used anywhere. I'm sorry if this is a bad explanation of what's going on, but I'm trying. :) I hope this can help you a bit to understand what I'm doing. Please, if I'm wrong about something, correct me.
Then a very simple test of this function could be something like this:
cout << "Enter a string:\n";
string str;
getline(cin, str);
int count = count_substrings(str);
cout << "Number of substrings == " << count << '\n';
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.
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.