How to find the lenght of the word in C++? [duplicate] - c++

This question already has answers here:
std::string length() and size() member functions
(4 answers)
Closed 2 years ago.
We have some word, that we should identify the length of. How can I do that?
Example INPUT: "hello" - without quotes;
Example OUTPUT: 5

If input is contained in a std::string you can find the length as stated by Ravi.
If it's a C string you find the length with
int len = strlen(INPUT);
In C/C++ upper case is normally used for constants so it's better to name the string input, not INPUT.

string str;
cin>>str;
//use this
cout<<str.length();
//or use this
cout<<str.size();
both of them will work fine.

There is one function to find length in C++.
You can try by using:
input.length()
Also remember, you need to include:
#include <iostream>
using namespace std;
Refer this document :
https://www.w3schools.com/cpp/cpp_strings_length.asp

You can use input.length() or input.size().
Or you can use this simple loop.
for (i = 0; str[i]; i++)
;
cout << i << endl;

Related

Why can't we assign the value to a non-initialized string within a for loop in c++? [duplicate]

This question already has answers here:
how to assign uninitialized string value from another string in C++
(3 answers)
Closed 7 months ago.
I'am learning c++ and I've a question like why can't we initalize a given string in a for loop.
string s, result;
cin >> s;
for(int i=0; i<s.length(); i++){
result[i] = s[i];
}
cout << result;
There simply won't be cout ofcourse. Because result string never got initialized in a for loop? Please explain why?
The following code, instead will be execute
result = s;
result has the length 0 so using the subscript operator to dereference and assign any element (except assigning \0 to the terminating \0) has undefined behavior.
If you want to append a char to the string:
result += s[i];

How can I seperate a string into individual characters in c++? [duplicate]

This question already has answers here:
For every character in string
(10 answers)
Closed 8 years ago.
As the title says, how can I seperate a string into individual characters in c++? For example, if the string is "cat" how can I separate that into the characters c,a, and t?
Thanks
By using the operator[]. e.g.
std::string cat{"cat"};
if(cat[0] == 'c')
//stuff
If you're using std::string you can simply use .c_str( ) that will give you an array of the chars.
In c++11 you could also do:
for( auto c : a )
{
cout << c << '\n';
}
http://ideone.com/UAyxTo
If you want to store them in a vector:
string str("cat");
vector<char> chars(str.begin(), str.end());
for (char c : chars)
cout << c << endl;

How to get length of a string using strlen function

I have following code that gets and prints a string.
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << str;
getch();
return 0;
}
But how to count the number of characters in this string using strlen() function?
For C++ strings, there's no reason to use strlen. Just use string::length:
std::cout << str.length() << std::endl;
You should strongly prefer this to strlen(str.c_str()) for the following reasons:
Clarity: The length() (or size()) member functions unambiguously give back the length of the string. While it's possible to figure out what strlen(str.c_str()) does, it forces the reader to pause for a bit.
Efficiency: length() and size() run in time O(1), while strlen(str.c_str()) will take Θ(n) time to find the end of the string.
Style: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use std::sort over qsort or std::lower_bound over bsearch, unless some other factors come into play that would affect performance.
The only reason I could think of where strlen would be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which strlen differs from string::length; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use string::find:
size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;
Function strlen shows the number of character before \0 and using it for std::string may report wrong length.
strlen(str.c_str()); // It may return wrong length.
In C++, a string can contain \0 within the characters but C-style-zero-terminated strings can not but at the end. If the std::string has a \0 before the last character then strlen reports a length less than the actual length.
Try to use .length() or .size(), I prefer second one since another standard containers have it.
str.size()
Use std::string::size or std::string::length (both are the same).
As you insist to use strlen, you can:
int size = strlen( str.c_str() );
note the usage of std::string::c_str, which returns const char*.
BUT strlen counts untill it hit \0 char and std::string can store such chars. In other words, strlen could sometimes lie for the size.
If you really, really want to use strlen(), then
cout << strlen(str.c_str()) << endl;
else the use of .length() is more in keeping with C++.
Manually:
int strlen(string s)
{
int len = 0;
while (s[len])
len++;
return len;
}
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char str[80];
int i;
cout<<"\n enter string:";
cin.getline(str,80);
int n=strlen(str);
cout<<"\n lenght is:"<<n;
getch();
return 0;
}
This is the program if you want to use strlen .
Hope this helps!
Simply use
int len=str.length();

How to accept case-insensitive inputs? [duplicate]

This question already has answers here:
Case-insensitive string comparison in C++ [closed]
(30 answers)
Closed 5 years ago.
How do you accept case-insensitive and allow embedded blanks in a user input? So the user can enter “hong konG” and get a correct match to the input.
I only have the input[0] = toupper(input[0]); which only accepts if the case sensitive is at the beginning of the word.
while(true){
cout << "Enter a city by name: "<< " ";
std::getline (std::cin,input);
if (input == "quit")
{
break;
}
input[0] = toupper (input[0]);
//....how do I loop to find all letter's in the input string variable?
}
You can use a loop to convert the entire string to upper case one character at a time, but a better solution is to use C++ standard library's transform function for that:
std::string hk = "hong konG";
std::transform(hk.begin(), hk.end(), hk.begin(), ::toupper);
This would apply ::toupper to all characters of your string, resulting in a string that reads "HONG KONG".
Demo on ideone.
for (auto& c : str)
c = std::toupper(c)
You can convert the whole string to upper-case like this
for (size_t i = 0; i < input.size(); ++i)
input[i] = toupper (input[i]);
The other suggestion to use std::transform is also a perfectly good solution.

how to show the character that come several time in string? [duplicate]

This question already has an answer here:
Counting characters in words in a C++ console application
(1 answer)
Closed 9 years ago.
Is there anyway to show that character s appears 5 times in the string is there any function to sort out the character and than show us that the character appears 5 or 6 times in the string.
#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you"
//now i want to show the l character appears several time.
//and i need help here.
system("pause");
}
You can use std::count
int lcount = std::count(a.begin(), a.end(), 'l');
Just keep counting using a pointer until nul character is reached and keep increasing an integer on successful comparison.
#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you";
char *p = &a[0];
int c = 0;
do
{
if(*p == 'l')
c++;
}while(*p++);
cout << c;
}
You can walk over any container, including a string and do what you like with it.
You could count how many instances of each character. You may want to consider ignoring whitespace.
std::string a("hello how are you");
std::map<char,int> count;
for(auto c : a)
{
++count[c];
}