Get the first character of a string [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The title pretty much says it all. I would like to know how to convert a one character string to a char.
Any help is appreciated!

That's the relatively simple:
char ch = str[0];
In other words, just grab the first character from the string, assuming it's not empty.
There's plenty of other stuff you could do, like handling an empty string or skipping leading whitespace, but the code above should be fine for your specific question.

You can do this using the subscript operator on the string, example:
string a = "hello";
char b;
if (!a.empty())
b = a[0];

std::string is a container of contiguous characters providing random access to their elements. There are at least three straight forward ways to retrieve the first character in a string
#include <string>
...
std::string string{ "Hello" };
char c1{ string[ 0 ] }, // undefined when called on an empty string
c2{ string.at( 0 ) }, // will throw if used on an empty string
c3{ string.front() }; // C++11 equivalent to string[ 0 ]
...

String is actually sequence of characters. And you can get any character you want from that sequence.
For example:
if you have string hello, world that is just sequence of characters:
h e l l o , w o r l d. Where index of first character h is 0 and index of last character is 11.
Same rules apply to one character string:
#include <cstdio>
int main() {
char text[] = "h";
printf("%s\n", text);
char first = text[0];
printf("%c\n", first);
return 0;
}
Here you have string h which is sequence of characters containing only one character. :D
Index of character h in that string is 0 so you can get that character with text[0].

Related

Finding matching letters in a string at same spots [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I need a code to compare two strings: word and ptw. Both strings only have one word, and are of equal length and same case. The code needs to check the first character of both words and see if they are same and it will do this untill the end of the word. Then it will output the amount of matching letters (I don't need to know the matching letters).
Example: If word is windows and ptw is winowes it should output 4 as w, i, n, and s match.
I have tried the following however it does not check the positions:
string matchingletters(string word, string ptw) {
string result = "";
sort(begin(word), end(word));
sort(begin(ptw), end(ptw));
std::string intersection;
std::set_intersection(begin(word), end(word), begin(ptw), end(ptw),
back_inserter(intersection));
string mlr = to_string(intersection.length());
result = mlr + result;
cout << result << endl;
return result;
}
The result this gives when word is kanton and ptw is balkon is 4.
It counts k even though k is at 0 position in word and 3 position at ptw and thus they are not in the same postion and should not be counted.
Assuming the two words have the same length and since you don't care which letters match you can simply iterate and count matching characters
unsigned matchingletters(const std::string& word, const std::string& ptw) {
assert(word.size() == ptw.size());
unsigned count{0};
for (size_t i = 0; i < word.size(); ++i) {
if(word[i] == ptw[i])
count++;
}
return count;
}

Adding char which is a math operator to random string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to add "+", "-", "*" etc. to a string but it doesn't work.
Lets say I have string "12 3 +" Then I use string tmp to get values between spaces like "12" "3" "+". my cout prints "12" and "3", but "+" is missing
int ONP() {
string wyrazenie;
getline(cin, wyrazenie);
string tmp;
for (int i = 0; i < wyrazenie.length(); ++i) {
if (!isspace(wyrazenie[i])) {
tmp += wyrazenie[i];
} else {
cout << tmp << endl;
SOME CODE.....
tmp.clear();
}
}
}
Issue is that + is your last character, so you won't go in else block for it.
std::cout temp after the loop would show your missing character:
Demo
Your loop will never display the last token of the string unless the string ends in a space. When you have "12 3 +" you read in the 12 see a space, print the 12 and clear the string. You do the same thing for 3. Then you get + but since that is the last character in the string you never run the else part of the if statement to print it out. You can fix this a few ways. You can check if temp is not empty after the loop and if it is not then handle that. You can rework your logic in the loop to handle when you are on the last character and it is not a space. You could add a space to the end of the input so it will end with a space and the loop works as is.
From the code you provided, I see an issue that would cause the last character to not be printed. This is because you are only printing tmp when the next character is a space. So "12 3 +" would print "12", "3". Then tmp contains the value "+" since its never printed nor cleared, but is never printed. If your input string is "12 3 + " (notice the space) the '+' char would be printed too.
This can be solved with printing and clearing tmp after the loop is done if tmp still contains any data.

remove non alphabet characters from string c++ [duplicate]

This question already has answers here:
How to strip all non alphanumeric characters from a string in c++?
(12 answers)
Closed 6 years ago.
I'm trying to remove all non alphabet characters from an inputed string in c++ and don't know how to. I know it probably involves ascii numbers because that's what we're learning about. I can't figure out how to remove them. We only learned up to loops and haven't started arrays yet. Not sure what to do.
If the string is Hello 1234 World&*
It would print HelloWorld
If you use std::string and STL, you can:
string s("Hello 1234 World&*");
s.erase(remove_if(s.begin(), s.end(), [](char c) { return !isalpha(c); } ), s.end());
http://ideone.com/OIsJmb
Note: If you want to be able to handle strings holding text in just about any language except English, or where programs use a locale other than the default, you can use isalpha(std::locale).
PS: If you use a c-style string such as char *, you can convert it to std::string by its constructor, and convert back by its member function c_str().
If you're working with C-style strings (e.g. char* str = "foobar") then you can't "remove" characters from a string trivially (as a string is just a sequence of characters stored sequentially in memory - removing a character means copying bytes forward to fill the empty space used by the deleted character.
You'd have to allocate space for a new string and copy characters into it as-needed. The problem is, you have to allocate memory before you fill it, so you'd over-allocate memory unless you do an initial pass to get a count of the number of characters remaining in the string.
Like so:
void BlatentlyObviousHomeworkExercise() {
char* str = "someString";
size_t strLength = ... // how `strLength` is set depends on how `str` gets its value, if it's a literal then using the `sizeof` operator is fine, otherwise use `strlen` (assuming it's a null-terminated string).
size_t finalLength = 0;
for(size_t i = 0; i < strLength; i++ ) {
char c = str[i]; // get the ith element of the `str` array.
if( IsAlphabetical(c) ) finalLength++;
}
char* filteredString = new char[ finalLength + 1 ]; // note I use `new[]` instead of `malloc` as this is C++, not C. Use the right idioms :) The +1 is for the null-terminator.
size_t filteredStringI = 0;
for(size_t i = 0; i < strLength; i++ ) {
char c = str[i];
if( IsAlphabetical(c) ) filteredString[ filteredStringI++ ] = c;
}
filteredString[ filteredStringI ] = '\0'; // set the null terminator
}
bool IsAlphabet(char c) { // `IsAlphabet` rather than `IsNonAlphabet` to avoid negatives in function names/behaviors for simplicity
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
I do not want to spoil the solution so I will not type out the code, only describe the solution. For your problem think of iterating through your string. Start with that. Then you need to decide if the currently selected character is part of the alphabet or not. You can do this numerous different ways. Checking ASCII values? Comparing against a string of the alphabet? Once you decide if it is a letter, then you need to rebuild the new string with that letter plus the valid letters before and after that you found or will find. Finally you need to display your new string.
If you look at an ascii table, you can see that A-Z is between 65-90 and a-z is between 97-122.
So, assuming that you only need to remove those characters (not accentuated), and not other characters from other languages for example, not represented in ascii, all you would need to do is loop the string, verify if each char is in these values and remove it.

decoding a character array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Given a character array in a URL format like
char *s="www.google.com\tsp finite.aspx"
While decoding it space should be replaced by %20 and thus the string becomes:
char *s="www.google.com\tsp%20finite.aspx"
We are not allowed to use a new character array but allowed to use some character variables for temporary use. Should not use any containers also. The array contains enough space to contain the decoded data so no need to worry about the more space to be taken.
I followed the Brute-Force mechanism where all the characters from the point of finding a space to the end of the array are to be swapped. But this is not the most efficient way to solve the problem.
Can any body tell me which is the best way (algorithm) to decrease the no. of swappings in order to acquire the solution.
I am assuming the string has been allocated using malloc
First calculate the number of spaces and the length of the string
Then the new length = old length + number of spaces * 2. Use realloc to expand the string.
The work backwards from the end and copy to the new length. When encountering space copy in %20 instead.
The main problem could be that swapping space with %20 will require moving the whole string 2 characters more .
Here's an idea :
Parse the whole string once, and count the number of spaces in the string
The new length of the array would be strlen(original) + 2*(nOfSpaces) (let's call it from now on NewLen)
Parse the whole string once again but starting backwards.
You will copy the previous string contents inside itself but at an offset until you hit a space
you will have a pointer starting at strlen(original) and one starting at NewLen
parse from strlen(original) backwards until you find a space (the substrLen will be subLen)
memcpy from [strlen(original)-curParsingindex] to [NewLen - curParsingIndex-2*(enteredSpaces)] sublen amount
Instead of copying the space, put %20 instead
This way you will avoid moving the string forward each time you hit a space.
Regarding step 4 , you might think about using a temporary variable for the sublen, since you might end up writing in the same memory zone by mistake (take an example where all the spaces are at the beginning).
This is a classic interview coding question; a good solution for this starts with a good interface for your solution. Something that works is:
char* replaceChar(char* in, char c)
char *in - string you want to decode
c - the char you want to replace with it's hexa value ASCII code ( HEX val ascii for ' ' is 0x20)
Pseudocode:
allocate a buffer the same size as the input buffer
get the index of the first occurrence of the char you want to replace (strcspn can help with that)
copy the content of the of the input up to the found index to the new buffer.
reallocate the new buffer size to newSize=oldSize+2
add % to the new string
repeat until you reach the end of the string.
return a pointer to the new string
You can also do it in place on the original string but that solution is a bit more complicated because you have to shift everything.
You can do it in two passes. The key idea is to first count the number of spaces and then move each character directly to its final position. In your approach you shift the remainder of the string at each occurrence of a space.
#include <stdio.h>
int main ()
{
char str[1000] = "www.example.com/hello world !";
int length;
int spaces;
int i;
char *ptr;
printf ("\"%s\"\n", str);
// pass 1:
// calculate length and count spaces
length = 0;
spaces = 0;
for (ptr = str; *ptr; ptr++) {
if (*ptr == ' ') {
spaces++;
}
length++;
}
// pass 2:
// transform string
// preserve terminating null character
ptr = str + length + 2 * spaces;
for (i = length; i >= 0; i--) {
char c = str[i];
if (c == ' ') {
*ptr-- = '0';
*ptr-- = '2';
*ptr-- = '%';
}
else {
*ptr-- = c;
}
}
printf ("\"%s\"\n", str);
return 0;
}

Removing Whitespace from string in C++ [duplicate]

This question already has answers here:
Remove spaces from std::string in C++
(19 answers)
Closed 9 years ago.
I am trying to do something that I imagine is quite straightforward but I am new to C/C++ so it is proving a little bit tricky.
Essentially I am trying to remove a single whitespace from data contained within a .txt. Each piece of data is on a separate line:
01011 0
11100 1
00001 0
and so on. I have been able to count the number of lines, and the size of each string (including the whitespace) however I want to lose the whitespace located within the data.
My code for reading the data in (including whitespace is as follows):
std::ifstream myfile ("random.txt");
std::string str;
if(myfile.is_open())
{
while (std::getline(myfile, str))
{
i++;
Size = str.size();
data_input[i] = str;
line_num = i;
array_count = line_num * Size;
}
i = 0;
}
I have looked at various other posts but can't seem to find one that fits what I am trying to achieve. Any help would be appreciated.
str.erase(str.find(' '), 1);
Explanation:
The call to str.find returns the position (index) of the space.
The call to str.erase removes one character, starting at that position.