कंप्यूटर प्रोग्रामिंग/स्ट्रिंग/स्विफ्ट
strings.swift
सम्पादन// This program splits a given comma-separated name into first and last name
// components and then displays the name.
import Foundation
func find(text: String, substring: String) -> Int
{
let range = text.range(of: substring)
if range != nil
{
return text.distance(from: text.startIndex, to: range!.lowerBound)
}
else
{
return (-1)
}
}
func substring(text: String, start: Int, end: Int) -> String
{
let startIndex = text.index(text.startIndex, offsetBy: start)
let endIndex = text.index(text.startIndex, offsetBy: end)
return text[startIndex...endIndex]
}
func getName() -> String
{
var name: String
var index: Int
repeat
{
print("Enter name (last, first):")
name = readLine()!
index = find(text: name, substring: ",")
} while (index < 0)
return name;
}
func getLast(name: String) -> String
{
var last: String
var index: Int
index = find(text: name, substring: ",")
if(index <= 0)
{
last = ""
}
else
{
last = substring(text: name, start: 0, end: index - 1)
}
return last;
}
func getFirst(name: String) -> String
{
var first: String
var index: Int
index = find(text: name, substring: ",")
if(index <= 0)
{
first = ""
}
else
{
first = substring(text: name, start: index + 1, end: name.characters.count - 1)
first = first.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
return first;
}
func displayName(first: String, last: String)
{
print("Hello " + first + " " + last + "!")
}
func main()
{
let name = getName()
let last = getLast(name: name)
let first = getFirst(name: name)
displayName(first: first, last: last)
}
main()
कोशिश करो
सम्पादननिम्न कोड मुफ्त ऑनलाइन विकास के वातावरण में से एक में ऊपर कॉपी और पेस्ट करो या अपने खुद के कम्पाइलर/इंटरप्रेटर/आईडीई का उपयोग करें।