C strings are essentially a combination of words used as a storage unit to contain alphanumeric data. The words in a string are associated with the following properties −
單字的位置從0開始。
Every word is associated with a different length.
#The characters combine together to form words, which eventually form sentences.
預設情況下,單字之間由空格字元分隔。
Every word contains at least one character.
在本文中,我們將開發一段程式碼,該程式碼以一個字串作為輸入,並顯示該字串中每個單字的最後一個字元。讓我們看下面的範例以更好地理解這個主題 -
範例1−
str − “Key word of a string” Output − y d f a g
例如,在這個字串的第四個單字中,只有一個字元出現,因此這是該字串的最後一個字元。
在這篇文章中,我們將開發一段程式碼,使用索引運算子提取每個單字的最後一個字符,然後分別存取前一個字符。
str.length()
在C 中,length()方法用於計算字串中的字元數。它按照字串的線性順序工作。
An input string, str is accepted.
The length of the string is computed using the length() method and stored in len variable.
#An iteration of the string is performed, using the for loop i.
Each time the character at ith position is extracted, stored in variable ch
#If this character is equivalent to the last index of the string, that is len-1, it is displayed.
#如果這個字符等於空格字符,則顯示第i-1個索引字符,因為它是前一個單字的最後一個字符。
下面的C 程式碼片段用於接受一個範例字串作為輸入,並計算字串中每個單字的最後一個字元 -
//including the required libraries #include<bits/stdc++.h> using namespace std; //compute last characters of a string void wordlastchar(string str) { // getting length of the string int len = str.length(); for (int i = 0; i <len ; i++) { char ch = str[i]; //last word of the string if (i == len - 1) cout<<ch; //if a space is encountered, marks the start of new word if (ch == ' ') { //print the previous character of the last word char lst = str[i-1]; cout<<lst<<" "; } } } //calling the method int main() { //taking a sample string string str = "Programming at TutorialsPoint"; cout<<"Input String : "<< str <<"\n"; //getfirstandlast characters cout<<"Last words of each word in a string : \n"; wordlastchar(str); }
Input String : Programming at TutorialsPoint Last words of each word in a string : g t t
在C 中,字串的句子格式中,所有單字都由空格字元分隔。字串的每個單字由大寫和小寫字元組成。使用相應的索引很容易提取這些字元並對其進行操作。
以上是列印字串中每個單字的最後一個字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!